using System;

class Program
{
    static bool a(bool value)
    {
        Console.WriteLine("a");
        return value;
    }

    static bool b(bool value)
    {
        Console.WriteLine("b");
        return value;
    }

    static void Main()
    {
        foreach (var i in new[] { false, true })
        {
            foreach (var j in new[] { false, true })
            {
                Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
                Console.WriteLine();
                Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
                Console.WriteLine();
            }
        }
    }
}

create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.


<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. </output>


using System;
using System.IO;
// Needed for the method.
using System.Text.RegularExpressions;
using System.Collections.Generic;

void Main()
{
   string blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
   List<string> words = new List<string>() {
      "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"
   };

   foreach(var word in words)
   {
      Console.WriteLine("{0}: {1}", word, CheckWord(blocks, word));
   }
}

bool CheckWord(string blocks, string word)
{
   for(int i = 0; i < word.Length; ++i)
   {
      int length = blocks.Length;
      Regex rgx = new Regex("([a-z]"+word[i]+"|"+word[i]+"[a-z])", RegexOptions.IgnoreCase);
      blocks = rgx.Replace(blocks, "", 1);
      if(blocks.Length == length) return false;
   }
   return true;
}

The code defines a function that checks if a given word can be spelled using a collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It uses regular expressions to perform the check and its time complexity is approximately m*(n - (m-1)/2), where n is the length of the blocks string and m is the length of the word string. The function is unoptimized.


using System.Text;
using System.Security.Cryptography;

byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());

implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5/Implementation for a scratch implementation.


using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main() {
        var oids = new [] {
            "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
            "1.3.6.1.4.1.11.2.17.5.2.0.79",
            "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
            "1.3.6.1.4.1.11150.3.4.0.1",
            "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
            "1.3.6.1.4.1.11150.3.4.0"
        };

        var comparer = Comparer<string>.Create((a, b) => {
            int c = a.Split('.').Select(int.Parse)
	        .Zip(b.Split('.').Select(int.Parse),
                    (i, j) => i.CompareTo(j)).FirstOrDefault(x => x != 0);
            return c != 0 ? c : a.Length.CompareTo(b.Length);
        });

        Array.Sort(oids, comparer);

        Console.WriteLine(string.Join(Environment.NewLine, oids));
    }
}

sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.


using System;
using System.IO;
using System.Net.Sockets;

class Program {
    static void Main(string[] args) {
        TcpClient tcp = new TcpClient("localhost", 256);
        StreamWriter writer = new StreamWriter(tcp.GetStream());

        writer.Write("hello socket world");
        writer.Flush();

        tcp.Close();
    }
}

using System.Text;
using System.Net.Sockets;

namespace SocketClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Connect("127.0.0.1", 1000);
            sock.Send(Encoding.ASCII.GetBytes("Hell, world!"));
            sock.Close();
        }
    }
}

"Opens a socket to localhost on port 256, sends the message 'hello socket world', and then closes the socket without exception handling."


Works with: Mono version 1.2
Works with: Visual C# version 2003
static void Main(string[] args)
{
    //First of all construct the SMTP client

    SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details
    SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false.
    SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
    SMTP.Credentials = new NetworkCredential("YourUserName", "YourPassword");
    MailMessage Mail = new MailMessage("yourEmail@address.com", "theirEmail@address.com");

    //Then we construct the message

    Mail.Subject = "Important Message";
    Mail.Body = "Hello over there"; //The body contains the string for your email
    //using "Mail.IsBodyHtml = true;" you can put an HTML page in your message body

    //Then we use the SMTP client to send the message

    SMTP.Send(Mail);

    Console.WriteLine("Message Sent");
}

Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.


using System;

class Program
{
    static void Main()
    {
        var number = 0;
        do
        {
            Console.WriteLine(Convert.ToString(number, 8));
        } while (++number > 0);
    }
}

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


Works with: C# version 2.0+

static void Swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}

int a = 1;
int b = 2;
Swap(ref a, ref b); // Type parameter is inferred.

Works with: C# version 7.0+

int a = 1;
int b = 2;
(a, b) = (b, a);

implement a generic swap function or operator that can interchange the values of any two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The implementation utilizes the concept of generics introduced in C# 2.0 and the support for tuples in C# 7.0.


using System;

class Program
{
    static string Reverse(string value)
    {
        char[] chars = value.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }

    static bool IsPalindrome(string value)
    {
        return value == Reverse(value);
    }

    static void Main(string[] args)
    {
        Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
    }
}

using System;
using System.Linq;

class Program
{
	static bool IsPalindrome(string text)
	{
		return text == new String(text.Reverse().ToArray());
	}

	static void Main(string[] args)
	{
		Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
	}
}

using System;

static class Program
{
    //As an extension method (must be declared in a static class)
    static bool IsPalindrome(this string sentence)
    {
        for (int l = 0, r = sentence.Length - 1; l < r; l++, r--)
            if (sentence[l] != sentence[r]) return false;
        return true;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("ingirumimusnocteetconsumimurigni".IsPalindrome());
    }
}

The code checks if a given sequence of characters (or bytes) is a palindrome, supporting Unicode characters. It also includes a function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code avoids string reversal for efficiency, instead comparing characters directly.


using System;

namespace RosettaCode {
    class Program {
        static void Main() {
            string temp = Environment.GetEnvironmentVariable("TEMP");
            Console.WriteLine("TEMP is " + temp);
        }
    }
}

"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


//Aamrun, 11th July 2022

using System;

namespace Sudan
{
  class Sudan
  {
  	static int F(int n,int x,int y) {
  		if (n == 0) {
    		return x + y;
  		}

  		else if (y == 0) {
    		return x;
  		}

  		return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);
	}

    static void Main(string[] args)
    {
      Console.WriteLine("F(1,3,3) = " + F(1,3,3));
    }
  }
}

F(1,3,3) = 35

implement the Sudan function, a non-primitive recursive function. It takes two inputs x and y, and returns their sum if the function is at the base case. If not at the base case, it recursively calls itself based on specific conditions.


#include <stdio.h>
#include <stdlib.h>

/* to read expanded code, run through cpp | indent -st */
#define DECL_STACK_TYPE(type, name)					\
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;	\
stk_##name stk_##name##_create(size_t init_size) {			\
	stk_##name s; if (!init_size) init_size = 4;			\
	s = malloc(sizeof(struct stk_##name##_t));			\
	if (!s) return 0;						\
	s->buf = malloc(sizeof(type) * init_size);			\
	if (!s->buf) { free(s); return 0; }				\
	s->len = 0, s->alloc = init_size;				\
	return s; }							\
int stk_##name##_push(stk_##name s, type item) {			\
	type *tmp;							\
	if (s->len >= s->alloc) {					\
		tmp = realloc(s->buf, s->alloc*2*sizeof(type));		\
		if (!tmp) return -1; s->buf = tmp;			\
		s->alloc *= 2; }					\
	s->buf[s->len++] = item;					\
	return s->len; }						\
type stk_##name##_pop(stk_##name s) {					\
	type tmp;							\
	if (!s->len) abort();						\
	tmp = s->buf[--s->len];						\
	if (s->len * 2 <= s->alloc && s->alloc >= 8) {			\
		s->alloc /= 2;						\
		s->buf = realloc(s->buf, s->alloc * sizeof(type));}	\
	return tmp; }							\
void stk_##name##_delete(stk_##name s) {				\
	free(s->buf); free(s); }

#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)

DECL_STACK_TYPE(int, int)

int main(void)
{
	int i;
	stk_int stk = stk_int_create(0);

	printf("pushing: ");
	for (i = 'a'; i <= 'z'; i++) {
		printf(" %c", i);
		stk_int_push(stk, i);
	}

	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	printf("\npoppoing:");
	while (stk_size(stk))
		printf(" %c", stk_int_pop(stk));
	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	/* stk_int_pop(stk); <-- will abort() */
	stk_int_delete(stk);
	return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdbool.h>

#define check_pointer(p) if (!p) {puts("Out of memory."); exit(EXIT_FAILURE);}

#define MINIMUM_SIZE 1
 /* Minimal stack size (expressed in number of elements) for which
 space is allocated. It should be at least 1. */
#define GROWTH_FACTOR 2
 /* How much more memory is allocated each time a stack grows
 out of its allocated segment. */
typedef int T;
 // The type of the stack elements.

typedef struct
 {T *bottom;
  T *top;
  T *allocated_top;} stack;

stack * new(void)
/* Creates a new stack. */
 {stack *s = malloc(sizeof(stack));
  check_pointer(s);
  s->bottom = malloc(MINIMUM_SIZE * sizeof(T));
  check_pointer(s->bottom);
  s->top = s->bottom - 1;
  s->allocated_top = s->bottom + MINIMUM_SIZE - 1;
  return s;}

void destroy(stack *s)
/* Frees all the memory used for a stack. */
 {free(s->bottom);
  free(s);}

bool empty(stack *s)
/* Returns true iff there are no elements on the stack. This
is different from the stack not having enough memory reserved
for even one element, which case is never allowed to arise. */
 {return s->top < s->bottom ? true : false;}

void push(stack *s, T x)
/* Puts a new element on the stack, enlarging the latter's
memory allowance if necessary. */
 {if (s->top == s->allocated_top)
     {ptrdiff_t qtty = s->top - s->bottom + 1;
      ptrdiff_t new_qtty = GROWTH_FACTOR * qtty;
      s->bottom = realloc(s->bottom, new_qtty * sizeof(T));
      check_pointer(s->bottom);
      s->top = s->bottom + qtty - 1;
      s->allocated_top = s->bottom + new_qtty - 1;}
  *(++s->top) = x;}

T pop(stack *s)
/* Removes and returns the topmost element. The result of popping
an empty stack is undefined. */
 {return *(s->top--);}

void compress(stack *s)
/* Frees any memory the stack isn't actually using. The
allocated portion still isn't allowed to shrink smaller than
MINIMUM_SIZE. If all the stack's memory is in use, nothing
happens. */
 {if (s->top == s->allocated_top) return;
  ptrdiff_t qtty = s->top - s->bottom + 1;
  if (qtty < MINIMUM_SIZE) qtty = MINIMUM_SIZE;
  size_t new_size = qtty * sizeof(T);
  s->bottom = realloc(s->bottom, new_size);
  check_pointer(s->bottom);
  s->allocated_top = s->bottom + qtty - 1;}

implement a stack data structure with basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty). The stack follows a Last In, First Out (LIFO) access policy.


long long fibb(long long a, long long b, int n) {
    return (--n>0)?(fibb(b, a+b, n)):(a);
}

long long int fibb(int n) {
	int fnow = 0, fnext = 1, tempf;
	while(--n>0){
		tempf = fnow + fnext;
		fnow = fnext;
		fnext = tempf;
		}
		return fnext;
}

#include <tgmath.h>
#define PHI ((1 + sqrt(5))/2)

long long unsigned fib(unsigned n) {
    return floor( (pow(PHI, n) - pow(1 - PHI, n))/sqrt(5) );
}
Works with: gcc version version 4.1.2 20080704 (Red Hat 4.1.2-44)
#include <stdio.h>
typedef enum{false=0, true=!0} bool;
typedef void iterator;

#include <setjmp.h>
/* declare label otherwise it is not visible in sub-scope */
#define LABEL(label) jmp_buf label; if(setjmp(label))goto label;
#define GOTO(label) longjmp(label, true)

/* the following line is the only time I have ever required "auto" */
#define FOR(i, iterator) { auto bool lambda(i); yield_init = (void *)λ iterator; bool lambda(i)
#define DO {
#define     YIELD(x) if(!yield(x))return
#define     BREAK    return false
#define     CONTINUE return true
#define OD CONTINUE; } }

static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) bool (*yield)(type) = yield_init

iterator fibonacci(int stop){
    YIELDS(int);
    int f[] = {0, 1};
    int i;
    for(i=0; i<stop; i++){
        YIELD(f[i%2]);
        f[i%2]=f[0]+f[1];
    }
}

main(){
  printf("fibonacci: ");
  FOR(int i, fibonacci(16)) DO
    printf("%d, ",i);
  OD;
  printf("...\n");
}

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


#include <stdio.h>
#include <stdlib.h>

int even_sel(int x) { return !(x & 1); }
int tri_sel(int x) { return x % 3; }

/* using a predicate function sel() to select elements */
int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)
{
	int i, j, *out;

	if (inplace)	out = in;
	else		out = malloc(sizeof(int) * len);

	for (i = j = 0; i < len; i++)
		if (sel(in[i]))
			out[j++] = in[i];

	if (!inplace && j < len)
		out = realloc(out, sizeof(int) * j);

	*outlen = j;
	return out;
}

int main()
{
	int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int i, len;

	int *even = grep(in, 10, &len, even_sel, 0);
	printf("Filtered even:");
	for (i = 0; i < len; i++) printf(" %d", even[i]);
	printf("\n");

	grep(in, 8, &len, tri_sel, 1);
	printf("In-place filtered not multiple of 3:");
	for (i = 0; i < len; i++) printf(" %d", in[i]);

	printf("\n");

	return 0;
}

select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


/*
 * RosettaCode: Substring, C89
 *
 * In this task display a substring: starting from n characters in and of m
 * length; starting from n characters in, up to the end of the string; whole
 * string minus last character; starting from a known character within the
 * string and of m length; starting from a known substring within the string
 * and of m length.
 *
 * This example program DOES NOT make substrings. The program simply displays
 * certain parts of the input string.
 *
 */
#define _CRT_SECURE_NO_WARNINGS /* MSVS compilers need this */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * Put no more than m characters from string to standard output.
 *
 * It is worth noting that printf("%*s",width,string) does not limit the number
 * of characters to be printed.
 *
 * @param string null terminated string
 * @param m      number of characters to display
 */
void putm(char* string, size_t m)
{
    while(*string && m--)
        putchar(*string++);
}

int main(void)
{

    char string[] =
        "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."

    int n = 3;
    int m = 4;
    char knownCharacter = '(';
    char knownSubstring[] = "encodings";

    putm(string+n-1, m );                       putchar('\n');
    puts(string+n+1);                           putchar('\n');
    putm(string, strlen(string)-1);             putchar('\n');
    putm(strchr(string, knownCharacter), m );   putchar('\n');
    putm(strstr(string, knownSubstring), m );   putchar('\n');

    return EXIT_SUCCESS;
}

/*
 * RosettaCode: Substring, C89, Unicode
 *
 * In this task display a substring: starting from n characters in and of m
 * length; starting from n characters in, up to the end of the string; whole
 * string minus last character; starting from a known character within the
 * string and of m length; starting from a known substring within the string
 * and of m length.
 *
 * This example program DOES NOT make substrings. The program simply displays
 * certain parts of the input string.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * Put all characters from string to standard output AND write newline.
 * BTW, _putws may not be avaliable.
 */
void put(wchar_t* string)
{
    while(*string)
        putwchar(*string++);
    putwchar(L'\n');
}

/*
 * Put no more than m characters from string to standard output AND newline.
 */
void putm(wchar_t* string, size_t m)
{
    while(*string && m--)
        putwchar(*string++);
    putwchar(L'\n');
}

int main(void)
{
    wchar_t string[] =
        L"Programs for other encodings (such as 8-bit ASCII).";

    int n = 3;
    int m = 4;
    wchar_t knownCharacter = L'(';
    wchar_t knownSubstring[] = L"encodings";

    putm(string+n-1,m);
    put (string+n+1);
    putm(string, wcslen(string)-1);
    putm(wcschr(string, knownCharacter), m );
    putm(wcsstr(string, knownSubstring), m );

    return EXIT_SUCCESS;
}

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *substring(const char *s, size_t n, ptrdiff_t m)
{
  char *result;
  /* check for null s */
  if (NULL == s)
    return NULL;
  /* negative m to mean 'up to the mth char from right' */
  if (m < 0)
    m = strlen(s) + m - n + 1;

  /* n < 0 or m < 0 is invalid */
  if (n < 0 || m < 0)
    return NULL;

  /* make sure string does not end before n
   * and advance the "s" pointer to beginning of substring */
  for ( ; n > 0; s++, n--)
    if (*s == '\0')
      /* string ends before n: invalid */
      return NULL;

  result = malloc(m+1);
  if (NULL == result)
    /* memory allocation failed */
    return NULL;
  result[0]=0;
  strncat(result, s, m); /* strncat() will automatically add null terminator
                          * if string ends early or after reading m characters */
  return result;
}

char *str_wholeless1(const char *s)
{
  return substring(s, 0, strlen(s) - 1);
}

char *str_fromch(const char *s, int ch, ptrdiff_t m)
{
  return substring(s, strchr(s, ch) - s, m);
}

char *str_fromstr(const char *s, char *in, ptrdiff_t m)
{
  return substring(s, strstr(s, in) - s , m);
}

#define TEST(A) do {		\
    char *r = (A);		\
    if (NULL == r)		\
      puts("--error--");	\
    else {			\
      puts(r);			\
      free(r);			\
    }				\
  } while(0)

int main()
{
  const char *s = "hello world shortest program";

  TEST( substring(s, 12, 5) );		// get "short"
  TEST( substring(s, 6, -1) );		// get "world shortest program"
  TEST( str_wholeless1(s) );		// "... progra"
  TEST( str_fromch(s, 'w', 5) );	// "world"
  TEST( str_fromstr(s, "ro", 3) );	// "rog"

  return 0;
}

- Extracts a substring starting from the nth character of a specific length m.
- Extracts a substring starting from the nth character up to the end of the string.
- Returns the entire string excluding the last character.
- Extracts a substring starting from a known character within the string of length m.
- Extracts a substring starting from a known substring within the string of length m.
- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.
- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.


#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>

const char *sa = "abcdef";
const char *su = "as⃝df̅"; /* Should be in your native locale encoding. Mine is UTF-8 */

int is_comb(wchar_t c)
{
	if (c >= 0x300 && c <= 0x36f) return 1;
	if (c >= 0x1dc0 && c <= 0x1dff) return 1;
	if (c >= 0x20d0 && c <= 0x20ff) return 1;
	if (c >= 0xfe20 && c <= 0xfe2f) return 1;
	return 0;
}

wchar_t* mb_to_wchar(const char *s)
{
	wchar_t *u;
	size_t len = mbstowcs(0, s, 0) + 1;
	if (!len) return 0;

	u = malloc(sizeof(wchar_t) * len);
	mbstowcs(u, s, len);
	return u;
}

wchar_t* ws_reverse(const wchar_t* u)
{
	size_t len, i, j;
	wchar_t *out;
	for (len = 0; u[len]; len++);
	out = malloc(sizeof(wchar_t) * (len + 1));
	out[len] = 0;
	j = 0;
	while (len) {
		for (i = len - 1; i && is_comb(u[i]); i--);
		wcsncpy(out + j, u + i, len - i);
		j += len - i;
		len = i;
	}
	return out;
}

char *mb_reverse(const char *in)
{
	size_t len;
	char *out;
	wchar_t *u = mb_to_wchar(in);
	wchar_t *r = ws_reverse(u);
	len = wcstombs(0, r, 0) + 1;
	out = malloc(len);
	wcstombs(out, r, len);
	free(u);
	free(r);
	return out;
}

int main(void)
{
	setlocale(LC_CTYPE, "");

	printf("%s => %s\n", sa, mb_reverse(sa));
	printf("%s => %s\n", su, mb_reverse(su));
	return 0;
}

Reverses a given string while preserving Unicode combining characters. For instance, it transforms "asdf" to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef struct {
    int vertex;
    int weight;
} edge_t;

typedef struct {
    edge_t **edges;
    int edges_len;
    int edges_size;
    int dist;
    int prev;
    int visited;
} vertex_t;

typedef struct {
    vertex_t **vertices;
    int vertices_len;
    int vertices_size;
} graph_t;

typedef struct {
    int *data;
    int *prio;
    int *index;
    int len;
    int size;
} heap_t;

void add_vertex (graph_t *g, int i) {
    if (g->vertices_size < i + 1) {
        int size = g->vertices_size * 2 > i ? g->vertices_size * 2 : i + 4;
        g->vertices = realloc(g->vertices, size * sizeof (vertex_t *));
        for (int j = g->vertices_size; j < size; j++)
            g->vertices[j] = NULL;
        g->vertices_size = size;
    }
    if (!g->vertices[i]) {
        g->vertices[i] = calloc(1, sizeof (vertex_t));
        g->vertices_len++;
    }
}

void add_edge (graph_t *g, int a, int b, int w) {
    a = a - 'a';
    b = b - 'a';
    add_vertex(g, a);
    add_vertex(g, b);
    vertex_t *v = g->vertices[a];
    if (v->edges_len >= v->edges_size) {
        v->edges_size = v->edges_size ? v->edges_size * 2 : 4;
        v->edges = realloc(v->edges, v->edges_size * sizeof (edge_t *));
    }
    edge_t *e = calloc(1, sizeof (edge_t));
    e->vertex = b;
    e->weight = w;
    v->edges[v->edges_len++] = e;
}

heap_t *create_heap (int n) {
    heap_t *h = calloc(1, sizeof (heap_t));
    h->data = calloc(n + 1, sizeof (int));
    h->prio = calloc(n + 1, sizeof (int));
    h->index = calloc(n, sizeof (int));
    return h;
}

void push_heap (heap_t *h, int v, int p) {
    int i = h->index[v] == 0 ? ++h->len : h->index[v];
    int j = i / 2;
    while (i > 1) {
        if (h->prio[j] < p)
            break;
        h->data[i] = h->data[j];
        h->prio[i] = h->prio[j];
        h->index[h->data[i]] = i;
        i = j;
        j = j / 2;
    }
    h->data[i] = v;
    h->prio[i] = p;
    h->index[v] = i;
}

int min (heap_t *h, int i, int j, int k) {
    int m = i;
    if (j <= h->len && h->prio[j] < h->prio[m])
        m = j;
    if (k <= h->len && h->prio[k] < h->prio[m])
        m = k;
    return m;
}

int pop_heap (heap_t *h) {
    int v = h->data[1];
    int i = 1;
    while (1) {
        int j = min(h, h->len, 2 * i, 2 * i + 1);
        if (j == h->len)
            break;
        h->data[i] = h->data[j];
        h->prio[i] = h->prio[j];
        h->index[h->data[i]] = i;
        i = j;
    }
    h->data[i] = h->data[h->len];
    h->prio[i] = h->prio[h->len];
    h->index[h->data[i]] = i;
    h->len--;
    return v;
}

void dijkstra (graph_t *g, int a, int b) {
    int i, j;
    a = a - 'a';
    b = b - 'a';
    for (i = 0; i < g->vertices_len; i++) {
        vertex_t *v = g->vertices[i];
        v->dist = INT_MAX;
        v->prev = 0;
        v->visited = 0;
    }
    vertex_t *v = g->vertices[a];
    v->dist = 0;
    heap_t *h = create_heap(g->vertices_len);
    push_heap(h, a, v->dist);
    while (h->len) {
        i = pop_heap(h);
        if (i == b)
            break;
        v = g->vertices[i];
        v->visited = 1;
        for (j = 0; j < v->edges_len; j++) {
            edge_t *e = v->edges[j];
            vertex_t *u = g->vertices[e->vertex];
            if (!u->visited && v->dist + e->weight <= u->dist) {
                u->prev = i;
                u->dist = v->dist + e->weight;
                push_heap(h, e->vertex, u->dist);
            }
        }
    }
}

void print_path (graph_t *g, int i) {
    int n, j;
    vertex_t *v, *u;
    i = i - 'a';
    v = g->vertices[i];
    if (v->dist == INT_MAX) {
        printf("no path\n");
        return;
    }
    for (n = 1, u = v; u->dist; u = g->vertices[u->prev], n++)
        ;
    char *path = malloc(n);
    path[n - 1] = 'a' + i;
    for (j = 0, u = v; u->dist; u = g->vertices[u->prev], j++)
        path[n - j - 2] = 'a' + u->prev;
    printf("%d %.*s\n", v->dist, n, path);
}

int main () {
    graph_t *g = calloc(1, sizeof (graph_t));
    add_edge(g, 'a', 'b', 7);
    add_edge(g, 'a', 'c', 9);
    add_edge(g, 'a', 'f', 14);
    add_edge(g, 'b', 'c', 10);
    add_edge(g, 'b', 'd', 15);
    add_edge(g, 'c', 'd', 11);
    add_edge(g, 'c', 'f', 2);
    add_edge(g, 'd', 'e', 6);
    add_edge(g, 'e', 'f', 9);
    dijkstra(g, 'a', 'e');
    print_path(g, 'e');
    return 0;
}

Implement Dijkstra's algorithm to determine the shortest path from a given source node to all other nodes in a directed, weighted graph. The algorithm outputs a set of edges representing the shortest path to each reachable node. It also includes functionality to interpret the output and display the shortest path from the source node to specific nodes. The graph's vertices and edges are represented using either numbers or names. The priority queue used in the algorithm is implemented as a binary heap.


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct node {
	int payload;
	int height;
	struct node * kid[2];
} dummy = { 0, 0, {&dummy, &dummy} }, *nnil = &dummy;
// internally, nnil is the new nul

struct node *new_node(int value)
{
	struct node *n = calloc(1, sizeof *n);
	*n = (struct node) { value, 1, {nnil, nnil} };
	return n;
}

int max(int a, int b) { return a > b ? a : b; }
inline void set_height(struct node *n) {
	n->height = 1 + max(n->kid[0]->height, n->kid[1]->height);
}

inline int ballance(struct node *n) {
	return n->kid[0]->height - n->kid[1]->height;
}

// rotate a subtree according to dir; if new root is nil, old root is freed
struct node * rotate(struct node **rootp, int dir)
{
	struct node *old_r = *rootp, *new_r = old_r->kid[dir];

	if (nnil == (*rootp = new_r))
		free(old_r);
	else {
		old_r->kid[dir] = new_r->kid[!dir];
		set_height(old_r);
		new_r->kid[!dir] = old_r;
	}
	return new_r;
}

void adjust_balance(struct node **rootp)
{
	struct node *root = *rootp;
	int b = ballance(root)/2;
	if (b) {
		int dir = (1 - b)/2;
		if (ballance(root->kid[dir]) == -b)
			rotate(&root->kid[dir], !dir);
		root = rotate(rootp, dir);
	}
	if (root != nnil) set_height(root);
}

// find the node that contains value as payload; or returns 0
struct node *query(struct node *root, int value)
{
	return root == nnil
		? 0
		: root->payload == value
			? root
			: query(root->kid[value > root->payload], value);
}

void insert(struct node **rootp, int value)
{
	struct node *root = *rootp;

	if (root == nnil)
		*rootp = new_node(value);
	else if (value != root->payload) { // don't allow dup keys
		insert(&root->kid[value > root->payload], value);
		adjust_balance(rootp);
	}
}

void delete(struct node **rootp, int value)
{
	struct node *root = *rootp;
	if (root == nnil) return; // not found

	// if this is the node we want, rotate until off the tree
	if (root->payload == value)
		if (nnil == (root = rotate(rootp, ballance(root) < 0)))
			return;

	delete(&root->kid[value > root->payload], value);
	adjust_balance(rootp);
}

// aux display and verification routines, helpful but not essential
struct trunk {
	struct trunk *prev;
	char * str;
};

void show_trunks(struct trunk *p)
{
	if (!p) return;
	show_trunks(p->prev);
	printf("%s", p->str);
}

// this is very haphazzard
void show_tree(struct node *root, struct trunk *prev, int is_left)
{
	if (root == nnil) return;

	struct trunk this_disp = { prev, "    " };
	char *prev_str = this_disp.str;
	show_tree(root->kid[0], &this_disp, 1);

	if (!prev)
		this_disp.str = "---";
	else if (is_left) {
		this_disp.str = ".--";
		prev_str = "   |";
	} else {
		this_disp.str = "`--";
		prev->str = prev_str;
	}

	show_trunks(&this_disp);
	printf("%d
", root->payload);

	if (prev) prev->str = prev_str;
	this_disp.str = "   |";

	show_tree(root->kid[1], &this_disp, 0);
	if (!prev) puts("");
}

int verify(struct node *p)
{
	if (p == nnil) return 1;

	int h0 = p->kid[0]->height, h1 = p->kid[1]->height;
	int b = h0 - h1;

	if (p->height != 1 + max(h0, h1) || b < -1 || b > 1) {
		printf("node %d bad, balance %d
", p->payload, b);
		show_tree(p, 0, 0);
		abort();
	}
	return verify(p->kid[0]) && verify(p->kid[1]);
}

#define MAX_VAL 32
int main(void)
{
	int x;
	struct node *root = nnil;

	srand(time(0));

	for (x = 0; x < 10 * MAX_VAL; x++) {
		// random insertion and deletion
		if (rand()&1)	insert(&root, rand()%MAX_VAL);
		else		delete(&root, rand()%MAX_VAL);

		verify(root);
	}

	puts("Tree is:");
	show_tree(root, 0, 0);

	puts("
Querying values:");
	for (x = 0; x < MAX_VAL; x++) {
		struct node *p = query(root, x);
		if (p)	printf("%2d found: %p %d
", x, p, p->payload);
	}

	for (x = 0; x < MAX_VAL; x++) {
		delete(&root, x);
		verify(root);
	}

	puts("
After deleting all values, tree is:");
	show_tree(root, 0, 0);

	return 0;
}

Implement an AVL tree, a self-balancing binary search tree where the heights of two child subtrees of any node differ by at most one. The code includes operations for lookup, insertion, and deletion, all of which take O(log n) time. The tree is rebalanced as needed through tree rotations. Duplicate node keys are not allowed. The code also provides comparison with red-black trees.


#include<stdio.h>
#include<math.h>

typedef struct{
	double x,y;
	}point;

double distance(point p1,point p2)
{
	return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}

void findCircles(point p1,point p2,double radius)
{
	double separation = distance(p1,p2),mirrorDistance;

	if(separation == 0.0)
	{
		radius == 0.0 ? printf("\nNo circles can be drawn through (%.4f,%.4f)",p1.x,p1.y):
							 printf("\nInfinitely many circles can be drawn through (%.4f,%.4f)",p1.x,p1.y);
	}

	else if(separation == 2*radius)
	{
		printf("\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius);
	}

	else if(separation > 2*radius)
	{
		printf("\nGiven points are farther away from each other than a diameter of a circle with radius %.4f",radius);
	}

	else
	{
		mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2));

		printf("\nTwo circles are possible.");
		printf("\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius);
	}
}

int main()
{
    int i;

    point cases[] =
    {	{0.1234, 0.9876},    {0.8765, 0.2345},
	{0.0000, 2.0000},    {0.0000, 0.0000},
	{0.1234, 0.9876},    {0.1234, 0.9876},
	{0.1234, 0.9876},    {0.8765, 0.2345},
	{0.1234, 0.9876},    {0.1234, 0.9876}
    };

    double radii[] = {2.0,1.0,2.0,0.5,0.0};

    for(i=0;i<5;i++)
    {
	printf("\nCase %d)",i+1);
	findCircles(cases[2*i],cases[2*i+1],radii[i]);
    }

    return 0;
}

test run:
Case 1)
Two circles are possible.
Circle C1 with center (1.8631,1.9742), radius 2.0000 and Circle C2 with center (-0.8632,-0.7521), radius 2.0000
Case 2)
Given points are opposite ends of a diameter of the circle with center (0.0000,1.0000) and radius 1.0000
Case 3)
Infinitely many circles can be drawn through (0.1234,0.9876)
Case 4)
Given points are farther away from each other than a diameter of a circle with radius 0.5000
Case 5)
No circles can be drawn through (0.1234,0.9876)

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


implement the main step of the GOST 28147-89 encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using the replacement table, and returning an encrypted block. The version includes a packed replacement table.


int main(){
	time_t t;
	int a, b;
	srand((unsigned)time(&t));
	for(;;){
		a = rand() % 20;
		printf("%d\n", a);
		if(a == 10)
			break;
		b = rand() % 20;
		printf("%d\n", b);
	}
	return 0;
}

12
18
2
8
10
18
9
9
4
10

generates and prints random numbers from 0 to 19. If the generated number is 10, it stops the loop. If not, it generates and prints a second random number before restarting the loop. The loop runs indefinitely if 10 is never generated as the first number.


int isPrime(int n){
	if (n%2==0) return n==2;
	if (n%3==0) return n==3;
	int d=5;
	while(d*d<=n){
		if(n%d==0) return 0;
		d+=2;
		if(n%d==0) return 0;
		d+=4;}
	return 1;}

main() {int i,d,p,r,q=929;
	if (!isPrime(q)) return 1;
	r=q;
	while(r>0) r<<=1;
	d=2*q+1;
	do { 	for(p=r, i= 1; p; p<<= 1){
			i=((long long)i * i) % d;
			if (p < 0) i *= 2;
			if (i > d) i -= d;}
		if (i != 1) d += 2*q;
		else break;
	} while(1);
	printf("2^%d - 1 = 0 (mod %d)\n", q, d);}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


Library: LibXML

#include <libxml/parser.h>
#include <libxml/xpath.h>

xmlDocPtr getdoc (char *docname) {
	xmlDocPtr doc;
	doc = xmlParseFile(docname);

	return doc;
}

xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){

	xmlXPathContextPtr context;
	xmlXPathObjectPtr result;

	context = xmlXPathNewContext(doc);

	result = xmlXPathEvalExpression(xpath, context);
	xmlXPathFreeContext(context);

	return result;
}

int main(int argc, char **argv) {

	if (argc <= 2) {
		printf("Usage: %s <XML Document Name> <XPath expression>\n", argv[0]);
		return 0;
	}

	char *docname;
	xmlDocPtr doc;
	xmlChar *xpath = (xmlChar*) argv[2];
	xmlNodeSetPtr nodeset;
	xmlXPathObjectPtr result;
	int i;
	xmlChar *keyword;

	docname = argv[1];
	doc = getdoc(docname);
	result = getnodeset (doc, xpath);
	if (result) {
		nodeset = result->nodesetval;
		for (i=0; i < nodeset->nodeNr; i++) {
		xmlNodePtr titleNode = nodeset->nodeTab[i];
		keyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);
		printf("Value %d: %s\n",i+1, keyword);
		xmlFree(keyword);
		}
		xmlXPathFreeObject (result);
	}
	xmlFreeDoc(doc);
	xmlCleanupParser();
	return 0;
}

C:\rosettaCode>xPather.exe testXML.xml //price
Value 1: 14.50
Value 2: 23.99
Value 3: 4.95
Value 4: 3.56

C:\rosettaCode>xPather.exe testXML.xml //name
Value 1: Invisibility Cream
Value 2: Levitation Salve
Value 3: Blork and Freen Instameal
Value 4: Grob winglets

The code takes an XML document and XPath expressions as inputs, and performs three specific queries: retrieving the first "item" element, printing out each "price" element, and generating an array of all "name" elements. It also includes error handling for incorrect invocations. The XML document used for testing is stored in testXML.xml.


#include <stdio.h>

typedef unsigned int set_t; /* probably 32 bits; change according to need */

void show_set(set_t x, const char *name)
{
	int i;
	printf("%s is:", name);
	for (i = 0; (1U << i) <= x; i++)
		if (x & (1U << i))
			printf(" %d", i);
	putchar('\n');
}

int main(void)
{
	int i;
	set_t a, b, c;

	a = 0; /* empty set */
	for (i = 0; i < 10; i += 3) /* add 0 3 6 9 to set a */
		a |= (1U << i);
	show_set(a, "a");

	for (i = 0; i < 5; i++)
		printf("\t%d%s in set a\n", i, (a & (1U << i)) ? "":" not");

	b = a;
	b |= (1U << 5); b |= (1U << 10); /* b is a plus 5, 10 */
	b &= ~(1U << 0);	/* sans 0 */
	show_set(b, "b");

	show_set(a | b, "union(a, b)");
	show_set(c = a & b, "c = common(a, b)");
	show_set(a & ~b, "a - b"); /* diff, not arithmetic minus */
	show_set(b & ~a, "b - a");
	printf("b is%s a subset of a\n", !(b & ~a) ? "" : " not");
	printf("c is%s a subset of a\n", !(c & ~a) ? "" : " not");

	printf("union(a, b) - common(a, b) %s union(a - b, b - a)\n",
		((a | b) & ~(a & b)) == ((a & ~b) | (b & ~a))
			? "equals" : "does not equal");

	return 0;
}

demonstrate various set operations such as set creation, checking if an element is in a set, union, intersection, difference, subset, and equality of two sets. The code also optionally shows other set operations and modifications to a mutable set. The implementation of the set can be done using an associative array, binary search tree, hash table, or binary bits. The code also considers the efficiency of the basic test operation. The type of set implementation depends on the datatype and use case. For small, non-negative integers, a bit field implementation is shown.


#include <stdio.h>

/* Calculate day of week in proleptic Gregorian calendar. Sunday == 0. */
int wday(int year, int month, int day)
{
	int adjustment, mm, yy;

	adjustment = (14 - month) / 12;
	mm = month + 12 * adjustment - 2;
	yy = year - adjustment;
	return (day + (13 * mm - 1) / 5 +
		yy + yy / 4 - yy / 100 + yy / 400) % 7;
}

int main()
{
	int y;

	for (y = 2008; y <= 2121; y++) {
		if (wday(y, 12, 25) == 0) printf("%04d-12-25\n", y);
	}

	return 0;
}

"Determines the years between 2008 and 2121 where Christmas falls on a Sunday using standard date handling libraries. The program also checks for any discrepancies in date handling across different programming languages, potentially caused by issues like y2k-like overflow. Zeller's Rule is used to calculate the day of the week due to known issues with C libraries."


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct {
	int m, n;
	double ** v;
} mat_t, *mat;

mat matrix_new(int m, int n)
{
	mat x = malloc(sizeof(mat_t));
	x->v = malloc(sizeof(double*) * m);
	x->v[0] = calloc(sizeof(double), m * n);
	for (int i = 0; i < m; i++)
		x->v[i] = x->v[0] + n * i;
	x->m = m;
	x->n = n;
	return x;
}

void matrix_delete(mat m)
{
	free(m->v[0]);
	free(m->v);
	free(m);
}

void matrix_transpose(mat m)
{
	for (int i = 0; i < m->m; i++) {
		for (int j = 0; j < i; j++) {
			double t = m->v[i][j];
			m->v[i][j] = m->v[j][i];
			m->v[j][i] = t;
		}
	}
}

mat matrix_copy(int n, double a[][n], int m)
{
	mat x = matrix_new(m, n);
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			x->v[i][j] = a[i][j];
	return x;
}

mat matrix_mul(mat x, mat y)
{
	if (x->n != y->m) return 0;
	mat r = matrix_new(x->m, y->n);
	for (int i = 0; i < x->m; i++)
		for (int j = 0; j < y->n; j++)
			for (int k = 0; k < x->n; k++)
				r->v[i][j] += x->v[i][k] * y->v[k][j];
	return r;
}

mat matrix_minor(mat x, int d)
{
	mat m = matrix_new(x->m, x->n);
	for (int i = 0; i < d; i++)
		m->v[i][i] = 1;
	for (int i = d; i < x->m; i++)
		for (int j = d; j < x->n; j++)
			m->v[i][j] = x->v[i][j];
	return m;
}

/* c = a + b * s */
double *vmadd(double a[], double b[], double s, double c[], int n)
{
	for (int i = 0; i < n; i++)
		c[i] = a[i] + s * b[i];
	return c;
}

/* m = I - v v^T */
mat vmul(double v[], int n)
{
	mat x = matrix_new(n, n);
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			x->v[i][j] = -2 *  v[i] * v[j];
	for (int i = 0; i < n; i++)
		x->v[i][i] += 1;

	return x;
}

/* ||x|| */
double vnorm(double x[], int n)
{
	double sum = 0;
	for (int i = 0; i < n; i++) sum += x[i] * x[i];
	return sqrt(sum);
}

/* y = x / d */
double* vdiv(double x[], double d, double y[], int n)
{
	for (int i = 0; i < n; i++) y[i] = x[i] / d;
	return y;
}

/* take c-th column of m, put in v */
double* mcol(mat m, double *v, int c)
{
	for (int i = 0; i < m->m; i++)
		v[i] = m->v[i][c];
	return v;
}

void matrix_show(mat m)
{
	for(int i = 0; i < m->m; i++) {
		for (int j = 0; j < m->n; j++) {
			printf(" %8.3f", m->v[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

void householder(mat m, mat *R, mat *Q)
{
	mat q[m->m];
	mat z = m, z1;
	for (int k = 0; k < m->n && k < m->m - 1; k++) {
		double e[m->m], x[m->m], a;
		z1 = matrix_minor(z, k);
		if (z != m) matrix_delete(z);
		z = z1;

		mcol(z, x, k);
		a = vnorm(x, m->m);
		if (m->v[k][k] > 0) a = -a;

		for (int i = 0; i < m->m; i++)
			e[i] = (i == k) ? 1 : 0;

		vmadd(x, e, a, e, m->m);
		vdiv(e, vnorm(e, m->m), e, m->m);
		q[k] = vmul(e, m->m);
		z1 = matrix_mul(q[k], z);
		if (z != m) matrix_delete(z);
		z = z1;
	}
	matrix_delete(z);
	*Q = q[0];
	*R = matrix_mul(q[0], m);
	for (int i = 1; i < m->n && i < m->m - 1; i++) {
		z1 = matrix_mul(q[i], *Q);
		if (i > 1) matrix_delete(*Q);
		*Q = z1;
		matrix_delete(q[i]);
	}
	matrix_delete(q[0]);
	z = matrix_mul(*Q, m);
	matrix_delete(*R);
	*R = z;
	matrix_transpose(*Q);
}

double in[][3] = {
	{ 12, -51,   4},
	{  6, 167, -68},
	{ -4,  24, -41},
	{ -1, 1, 0},
	{ 2, 0, 3},
};

int main()
{
	mat R, Q;
	mat x = matrix_copy(3, in, 5);
	householder(x, &R, &Q);

	puts("Q"); matrix_show(Q);
	puts("R"); matrix_show(R);

	// to show their product is the input matrix
	mat m = matrix_mul(Q, R);
	puts("Q * R"); matrix_show(m);

	matrix_delete(x);
	matrix_delete(R);
	matrix_delete(Q);
	matrix_delete(m);
	return 0;
}

The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.


#include <stdio.h>
#include <stdlib.h>

struct list_node {int x; struct list_node *next;};
typedef struct list_node node;

node * uniq(int *a, unsigned alen)
 {if (alen == 0) return NULL;
  node *start = malloc(sizeof(node));
  if (start == NULL) exit(EXIT_FAILURE);
  start->x = a[0];
  start->next = NULL;

  for (int i = 1 ; i < alen ; ++i)
     {node *n = start;
      for (;; n = n->next)
         {if (a[i] == n->x) break;
          if (n->next == NULL)
             {n->next = malloc(sizeof(node));
              n = n->next;
              if (n == NULL) exit(EXIT_FAILURE);
              n->x = a[i];
              n->next = NULL;
              break;}}}

  return start;}

int main(void)
   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
        printf("%d ", n->x);
    puts("");
    return 0;}

"Implements a function to remove duplicate elements from an array using three different approaches: 1) Utilizing a hash table, 2) Sorting elements and removing consecutive duplicates, 3) Checking each element against the rest of the list. The function returns the result as a linked list due to unknown size of the new data structure."


#include <stdio.h>

void quicksort(int *A, int len);

int main (void) {
  int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
  int n = sizeof a / sizeof a[0];

  int i;
  for (i = 0; i < n; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");

  quicksort(a, n);

  for (i = 0; i < n; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");

  return 0;
}

void quicksort(int *A, int len) {
  if (len < 2) return;

  int pivot = A[len / 2];

  int i, j;
  for (i = 0, j = len - 1; ; i++, j--) {
    while (A[i] < pivot) i++;
    while (A[j] > pivot) j--;

    if (i >= j) break;

    int temp = A[i];
    A[i]     = A[j];
    A[j]     = temp;
  }

  quicksort(A, i);
  quicksort(A + i, len - i);
}

implement the quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them together with the pivot. The algorithm can work in place by swapping elements within the array, avoiding additional memory allocation. The pivot selection method is not specified and can vary. The code also includes a variant of quicksort that works with randomized sort and separated components.


#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_BUF 50

int main(void)
{
  char buf[MAX_BUF];
  time_t seconds = time(NULL);
  struct tm *now = localtime(&seconds);
  const char *months[] = {"January", "February", "March", "April", "May", "June",
                          "July", "August", "September", "October", "November", "December"};

  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"};

  (void) printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
  (void) printf("%s, %s %d, %d\n",days[now->tm_wday], months[now->tm_mon],
               now->tm_mday, now->tm_year + 1900);
  /* using the strftime (the result depends on the locale) */
  (void) strftime(buf, MAX_BUF, "%A, %B %e, %Y", now);
  (void) printf("%s\n", buf);
  return EXIT_SUCCESS;
}

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


#include <stdio.h>

struct node {
	char *s;
	struct node* prev;
};

void powerset(char **v, int n, struct node *up)
{
	struct node me;

	if (!n) {
		putchar('[');
		while (up) {
			printf(" %s", up->s);
			up = up->prev;
		}
		puts(" ]");
	} else {
		me.s = *v;
		me.prev = up;
		powerset(v + 1, n - 1, up);
		powerset(v + 1, n - 1, &me);
	}
}

int main(int argc, char **argv)
{
	powerset(argv + 1, argc - 1, 0);
	return 0;
}

implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.


#include <stdio.h>

int main() {
    int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

    // There is a bug: "XL\0" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long...
    // Should be "XL" without \0 etc.
    //
    char roman[13][3] = {"M\0", "CM\0", "D\0", "CD\0", "C\0", "XC\0", "L\0", "XL\0", "X\0", "IX\0", "V\0", "IV\0", "I\0"};
    int N;

    printf("Enter arabic number:\n");
    scanf("%d", &N);
    printf("\nRoman number:\n");

    for (int i = 0; i < 13; i++) {
        while (N >= arabic[i]) {
            printf("%s", roman[i]);
            N -= arabic[i];
        }
    }
    return 0;
}

The code takes a positive integer as input and returns its equivalent in Roman numerals as a string. It handles each digit separately, starting from the leftmost and ignoring zeros. For example, it converts 1990 to MCMXC, 2008 to MMVIII, and 1666 to MDCLXVI.


int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */
float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */

#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))

long a2D_Array[3][5];    /* 3 rows, 5 columns. */
float my2Dfloats[][3] = {
   1.0, 2.0, 0.0,
   5.0, 1.0, 3.0 };
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(my2dFloats[0]))

int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements);  /* array of 10 integers */
if ( myArray != NULL )   /* check to ensure allocation succeeded. */
{
  /* allocation succeeded */
  /* at the end, we need to free the allocated memory */
  free(myArray);
}
                    /* calloc() additionally pre-initializes to all zeros */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
if (myShorts != NULL)....

myArray[0] = 1;
myArray[1] = 3;

printf("%d\n", myArray[1]);

*(array + index) = 1;
printf("%d\n", *(array + index));
3[array] = 5;

#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
   kernel += XSIZE;
   for (ix=-XSIZE; ix<=XSIZE; ix++) {
       kernel[ix] = f(ix);
   ....
   free(kernel-XSIZE);
   }
}

int *array = malloc (sizeof(int) * 20);
....
array = realloc(array, sizeof(int) * 40);

#include <stdlib.h>
#include <stdio.h>
typedef struct node{
  char value;
  struct node* next;
} node;
typedef struct charList{
  node* first;
  int size;
} charList;

charList createList(){
  charList foo = {.first = NULL, .size = 0};
  return foo;
}
int addEl(charList* list, char c){
  if(list != NULL){
    node* foo = (node*)malloc(sizeof(node));
    if(foo == NULL) return -1;
    foo->value = c; foo->next = NULL;
    if(list->first == NULL){
      list->first = foo;
    }else{
      node* it= list->first;
      while(it->next != NULL)it = it->next;
      it->next = foo;
    }
    list->size = list->size+1;
    return 0;
  }else return -1;
}
int removeEl(charList* list, int index){
    if(list != NULL && list->size > index){
      node* it = list->first;
      for(int i = 0; i < index-1; i++) it = it->next;
      node* el = it->next;
      it->next = el->next;
      free(el);
      list->size--;
      return 0;
    }else return -1;
}
char getEl(charList* list, int index){
    if(list != NULL && list->size > index){
        node* it = list->first;
        for(int i = 0; i < index; i++) it = it->next;
        return it->value;
    }else return '\0';
}
static void cleanHelp(node* el){
  if(el != NULL){
    if(el->next != NULL) cleanHelp(el->next);
    free(el);
  }
}
void clean(charList* list){
  cleanHelp(list->first);
  list->size = 0;
}

demonstrate the basic syntax of arrays in a specific programming language. The codes create both fixed-length and dynamic arrays, assign values to them, and retrieve an element from them. It also includes the initialization of a static array of integers, handling of autosized multidimensional arrays, and dynamic allocation of arrays when size is not known at compile time. The codes also showcase the usage of malloc(), calloc() and free() functions, array indexing, and absence of bounds check on the indexes. The codes also depict how to implement negative indexing and declare arrays with runtime known size. Lastly, it demonstrates the implementation of a linked list for characters.


#include <stdio.h>

int main(int argc, char **argv) {
  FILE *in, *out;
  int c;

  in = fopen("input.txt", "r");
  if (!in) {
    fprintf(stderr, "Error opening input.txt for reading.\n");
    return 1;
  }

  out = fopen("output.txt", "w");
  if (!out) {
    fprintf(stderr, "Error opening output.txt for writing.\n");
    fclose(in);
    return 1;
  }

  while ((c = fgetc(in)) != EOF) {
    fputc(c, out);
  }

  fclose(out);
  fclose(in);
  return 0;
}

Works with: POSIX
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

/* we just return a yes/no status; caller can check errno */
int copy_file(const char *in, const char *out)
{
	int ret = 0;
	int fin, fout;
	ssize_t len;
	char *buf[4096]; /* buffer size, some multiple of block size preferred */
	struct stat st;

	if ((fin  = open(in,  O_RDONLY)) == -1) return 0;
	if (fstat(fin, &st)) goto bail;

	/* open output with same permission */
	fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);
	if (fout == -1) goto bail;

	while ((len = read(fin, buf, 4096)) > 0)
		write(fout, buf, len);

	ret = len ? 0 : 1; /* last read should be 0 */

bail:	if (fin != -1)  close(fin);
	if (fout != -1) close(fout);
	return ret;
}

int main()
{
	copy_file("infile", "outfile");
	return 0;
}

If it's certain that mapping the whole input file into memory poses no problem (there can be all kinds of problems), this may be the most efficient:int copy_file(const char *in, const char *out)
{
	int ret = 0;
	int fin, fout;
	char *bi;
	struct stat st;

	if ((fin  = open(in,  O_RDONLY)) == -1) return 0;
	if (fstat(fin, &st)) goto bail;

	fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);
	if (fout == -1) goto bail;

	bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin,  0);

	ret = (bi == (void*)-1)
		? 0 : (write(fout, bi, st.st_size) == st.st_size);

bail:	if (fin != -1)  close(fin);
	if (fout != -1) close(fout);
	if (bi != (void*)-1) munmap(bi, st.st_size);
	return ret;
}

demonstrate how to read the contents of "input.txt" file into an intermediate variable and then write those contents into a new file called "output.txt". The codes also show how to handle file operations efficiently by copying larger blocks of data instead of one character at a time, using POSIX functions like open(), read(), write() and close().


/* Demonstrate toupper and tolower for
   standard C strings.
   This does not work for multibyte character sets. */
#include <ctype.h>
#include <stdio.h>

/* upper-cases s in place */
void str_toupper(char *s)
{
    while(*s)
    {
        *s=toupper(*s);
        s++;
    }
}

/* lower-cases s in place */
void str_tolower(char *s)
{
    while(*s)
    {
        *s=tolower(*s);
        s++;
    }
}

int main(int argc, char *argv[])
{
    char t[255]="alphaBETA";
    str_toupper(t);
    printf("uppercase: %s\n", t);
    str_tolower(t);
    printf("lowercase: %s\n", t);
    return 0;
}

The code takes a string "alphaBETA" and converts it to both upper-case and lower-case using the default encoding. It also demonstrates additional case conversion functions that may be included in the language's library, such as swapping case and capitalizing the first letter. The code uses locale-aware tolower and toupper functions.


#include <stdio.h>
#include <stdlib.h>
#include <values.h>
#include <math.h>
#include <string.h>

typedef struct { double x, y; } point_t, *point;

inline double dist(point a, point b)
{
        double dx = a->x - b->x, dy = a->y - b->y;
        return dx * dx + dy * dy;
}

inline int cmp_dbl(double a, double b)
{
        return a < b ? -1 : a > b ? 1 : 0;
}

int cmp_x(const void *a, const void *b) {
        return cmp_dbl( (*(const point*)a)->x, (*(const point*)b)->x );
}

int cmp_y(const void *a, const void *b) {
        return cmp_dbl( (*(const point*)a)->y, (*(const point*)b)->y );
}

double brute_force(point* pts, int max_n, point *a, point *b)
{
        int i, j;
        double d, min_d = MAXDOUBLE;

        for (i = 0; i < max_n; i++) {
                for (j = i + 1; j < max_n; j++) {
                        d = dist(pts[i], pts[j]);
                        if (d >= min_d ) continue;
                        *a = pts[i];
                        *b = pts[j];
                        min_d = d;
                }
        }
        return min_d;
}

double closest(point* sx, int nx, point* sy, int ny, point *a, point *b)
{
        int left, right, i;
        double d, min_d, x0, x1, mid, x;
        point a1, b1;
        point *s_yy;

        if (nx <= 8) return brute_force(sx, nx, a, b);

        s_yy  = malloc(sizeof(point) * ny);
        mid = sx[nx/2]->x;

        /* adding points to the y-sorted list; if a point's x is less than mid,
           add to the begining; if more, add to the end backwards, hence the
           need to reverse it */
        left = -1; right = ny;
        for (i = 0; i < ny; i++)
                if (sy[i]->x < mid) s_yy[++left] = sy[i];
                else                s_yy[--right]= sy[i];

        /* reverse the higher part of the list */
        for (i = ny - 1; right < i; right ++, i--) {
                a1 = s_yy[right]; s_yy[right] = s_yy[i]; s_yy[i] = a1;
        }

        min_d = closest(sx, nx/2, s_yy, left + 1, a, b);
        d = closest(sx + nx/2, nx - nx/2, s_yy + left + 1, ny - left - 1, &a1, &b1);

        if (d < min_d) { min_d = d; *a = a1; *b = b1; }
        d = sqrt(min_d);

        /* get all the points within distance d of the center line */
        left = -1; right = ny;
        for (i = 0; i < ny; i++) {
                x = sy[i]->x - mid;
                if (x <= -d || x >= d) continue;

                if (x < 0) s_yy[++left]  = sy[i];
                else       s_yy[--right] = sy[i];
        }

        /* compare each left point to right point */
        while (left >= 0) {
                x0 = s_yy[left]->y + d;

                while (right < ny && s_yy[right]->y > x0) right ++;
                if (right >= ny) break;

                x1 = s_yy[left]->y - d;
                for (i = right; i < ny && s_yy[i]->y > x1; i++)
                        if ((x = dist(s_yy[left], s_yy[i])) < min_d) {
                                min_d = x;
                                d = sqrt(min_d);
                                *a = s_yy[left];
                                *b = s_yy[i];
                        }

                left --;
        }

        free(s_yy);
        return min_d;
}

#define NP 1000000
int main()
{
        int i;
        point a, b;

        point pts  = malloc(sizeof(point_t) * NP);
        point* s_x = malloc(sizeof(point) * NP);
        point* s_y = malloc(sizeof(point) * NP);

        for(i = 0; i < NP; i++) {
                s_x[i] = pts + i;
                pts[i].x = 100 * (double) rand()/RAND_MAX;
                pts[i].y = 100 * (double) rand()/RAND_MAX;
        }

/*      printf("brute force: %g, ", sqrt(brute_force(s_x, NP, &a, &b)));
        printf("between (%f,%f) and (%f,%f)
", a->x, a->y, b->x, b->y);        */

        memcpy(s_y, s_x, sizeof(point) * NP);
        qsort(s_x, NP, sizeof(point), cmp_x);
        qsort(s_y, NP, sizeof(point), cmp_y);

        printf("min: %g; ", sqrt(closest(s_x, NP, s_y, NP, &a, &b)));
        printf("point (%f,%f) and (%f,%f)
", a->x, a->y, b->x, b->y);

        /* not freeing the memory, let OS deal with it.  Habit. */
        return 0;
}

The code provides two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute-force approach, iterating through each pair of points to find the pair with the minimum distance. The second function uses a recursive divide and conquer approach, sorting the points by x and y coordinates, and recursively finding the closest pair in the divided sets. The code returns the minimum distance and the pair of points.


#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) /* a.size() */
int ar[10];               /* Collection<Integer> ar = new ArrayList<Integer>(10); */
ar[0] = 1;                /* ar.set(0, 1); */
ar[1] = 2;

int* p;                   /* Iterator<Integer> p; Integer pValue; */
for (p=ar;                /* for( p = ar.itereator(), pValue=p.next(); */
       p<(ar+cSize(ar));  /*        p.hasNext(); */
       p++) {             /*        pValue=p.next() ) { */
  printf("%d\n",*p);      /*   System.out.println(pValue); */
}                         /* } */

int* ar;                  /* Collection<Integer> ar; */
int arSize;
arSize = (rand() % 6) + 1;
ar = calloc(arSize, sizeof(int) ); /* ar = new ArrayList<Integer>(arSize); */
ar[0] = 1;                /* ar.set(0, 1); */

int* p;                   /* Iterator<Integer> p; Integer pValue; */
for (p=ar;                /* p=ar.itereator(); for( pValue=p.next(); */
       p<(ar+arSize);     /*                         p.hasNext(); */
       p++) {             /*                         pValue=p.next() ) { */
  printf("%d\n",*p);      /*   System.out.println(pValue); */
}                         /* }    */

The code creates a collection and adds a few values to it. It utilizes various collection types such as arrays, malloced arrays, and strings. The code also demonstrates the use of pointer arithmetic in C language, and the creation of complex data structures using struct and pointers. The code also includes the usage of various data structures like linked lists, doubly-linked lists, queues, sets, stacks, and associative arrays.


#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char *name;
    double value;
    double weight;
    double volume;
} item_t;

item_t items[] = {
    {"panacea", 3000.0, 0.3, 0.025},
    {"ichor",   1800.0, 0.2, 0.015},
    {"gold",    2500.0, 2.0, 0.002},
};

int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;

void knapsack (int i, double value, double weight, double volume) {
    int j, m1, m2, m;
    if (i == n) {
        if (value > best_value) {
            best_value = value;
            for (j = 0; j < n; j++) {
                best[j] = count[j];
            }
        }
        return;
    }
    m1 = weight / items[i].weight;
    m2 = volume / items[i].volume;
    m = m1 < m2 ? m1 : m2;
    for (count[i] = m; count[i] >= 0; count[i]--) {
        knapsack(
            i + 1,
            value + count[i] * items[i].value,
            weight - count[i] * items[i].weight,
            volume - count[i] * items[i].volume
        );
    }
}

int main () {
    count = malloc(n * sizeof (int));
    best = malloc(n * sizeof (int));
    best_value = 0;
    knapsack(0, 0.0, 25.0, 0.25);
    int i;
    for (i = 0; i < n; i++) {
        printf("%d %s\n", best[i], items[i].name);
    }
    printf("best value: %.0f\n", best_value);
    free(count); free(best);
    return 0;
}

"Output: The code implements a solution to the unbounded Knapsack problem, where a traveler in Shangri La needs to maximize the value of items he can carry in his knapsack, given the weight and volume constraints. The code determines the optimal quantity of each item (panacea, ichor, gold) to take, considering their respective values, weights, and volumes. It provides one of the four possible solutions that maximize the total value."


#include <stdio.h>

int main()
{
  int i;
  for (i = 1; i <= 10; i++) {
    printf("%d", i);
    printf(i == 10 ? "\n" : ", ");
  }
  return 0;
}

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char input[] =
	"des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
	"dw01             ieee dw01 dware gtech\n"
	"dw02             ieee dw02 dware\n"
	"dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\n"
	"dw04             dw04 ieee dw01 dware gtech\n"
	"dw05             dw05 ieee dware\n"
	"dw06             dw06 ieee dware\n"
	"dw07             ieee dware\n"
	"dware            ieee dware\n"
	"gtech            ieee gtech\n"
	"ramlib           std ieee\n"
	"std_cell_lib     ieee std_cell_lib\n"
	"synopsys\n"
	"cycle_11	  cycle_12\n"
	"cycle_12	  cycle_11\n"
	"cycle_21	  dw01 cycle_22 dw02 dw03\n"
	"cycle_22	  cycle_21 dw01 dw04";

typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };

int get_item(item *list, int *len, const char *name)
{
	int i;
	item lst = *list;

	for (i = 0; i < *len; i++)
		if (!strcmp(lst[i].name, name)) return i;

	lst = *list = realloc(lst, ++*len * sizeof(item_t));
	i = *len - 1;
	memset(lst + i, 0, sizeof(item_t));
	lst[i].idx = i;
	lst[i].name = name;
	return i;
}

void add_dep(item it, int i)
{
	if (it->idx == i) return;
	it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
	it->deps[it->n_deps++] = i;
}

int parse_input(item *ret)
{
	int n_items = 0;
	int i, parent, idx;
	item list = 0;

	char *s, *e, *word, *we;
	for (s = input; ; s = 0) {
		if (!(s = strtok_r(s, "\n", &e))) break;

		for (i = 0, word = s; ; i++, word = 0) {
			if (!(word = strtok_r(word, " \t", &we))) break;
			idx = get_item(&list, &n_items, word);

			if (!i) parent = idx;
			else    add_dep(list + parent, idx);
		}
	}

	*ret = list;
	return n_items;
}

/* recursively resolve compile order; negative means loop */
int get_depth(item list, int idx, int bad)
{
	int max, i, t;

	if (!list[idx].deps)
		return list[idx].depth = 1;

	if ((t = list[idx].depth) < 0) return t;

	list[idx].depth = bad;
	for (max = i = 0; i < list[idx].n_deps; i++) {
		if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
			max = t;
			break;
		}
		if (max < t + 1) max = t + 1;
	}
	return list[idx].depth = max;
}

int main()
{
	int i, j, n, bad = -1, max, min;
	item items;
	n = parse_input(&items);

	for (i = 0; i < n; i++)
		if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;

	for (i = 0, max = min = 0; i < n; i++) {
		if (items[i].depth > max) max = items[i].depth;
		if (items[i].depth < min) min = items[i].depth;
	}

	printf("Compile order:\n");
	for (i = min; i <= max; i++) {
		if (!i) continue;

		if (i < 0) printf("   [unorderable]");
		else	   printf("%d:", i);

		for (j = 0; j < n || !putchar('\n'); j++)
			if (items[j].depth == i)
				printf(" %s", items[j].name);
	}

	return 0;
}

"Implement a function to return a valid compile order of VHDL libraries based on their dependencies. The function should handle self dependencies, un-orderable dependencies, and libraries with no dependents. It uses topological sorting, specifically Kahn's 1962 topological sort or depth-first search, to determine the order. The function also parses a multiline string to show the compile order."


#include <string.h>
#include <stdio.h>

int startsWith(const char* container, const char* target)
{
  size_t clen = strlen(container), tlen = strlen(target);
  if (clen < tlen)
    return 0;
  return strncmp(container, target, tlen) == 0;
}

int endsWith(const char* container, const char* target)
{
  size_t clen = strlen(container), tlen = strlen(target);
  if (clen < tlen)
    return 0;
  return strncmp(container + clen - tlen, target, tlen) == 0;
}

int doesContain(const char* container, const char* target)
{
  return strstr(container, target) != 0;
}

int main(void)
{
  printf("Starts with Test ( Hello,Hell ) : %d\n", startsWith("Hello","Hell"));
  printf("Ends with Test ( Code,ode ) : %d\n", endsWith("Code","ode"));
  printf("Contains Test ( Google,msn ) : %d\n", doesContain("Google","msn"));

  return 0;
}

The code performs three types of string matching operations: checking if the first string starts with the second string, if the first string contains the second string at any location, and if the first string ends with the second string. It also optionally prints the location of the match and handles multiple occurrences of a string. The matching is case sensitive and is implemented without using the string library, demonstrating that char strings are just pointers.


#include <stdio.h>

#define TRUE 1
#define FALSE 0

int a,b,c,d,e,f,g;
int lo,hi,unique,show;
int solutions;

void
bf()
{
    for (f = lo;f <= hi; f++)
        if ((!unique) ||
           ((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))
            {
            b = e + f - c;
            if ((b >= lo) && (b <= hi) &&
                   ((!unique) || ((b != a) && (b != c) &&
                   (b != d) && (b != g) && (b != e) && (b != f))))
                {
                solutions++;
                if (show)
                    printf("%d %d %d %d %d %d %d\n",a,b,c,d,e,f,g);
                }
            }
}

void
ge()
{
    for (e = lo;e <= hi; e++)
        if ((!unique) || ((e != a) && (e != c) && (e != d)))
            {
            g = d + e;
            if ((g >= lo) && (g <= hi) &&
                   ((!unique) || ((g != a) && (g != c) &&
                   (g != d) && (g != e))))
                bf();
            }
}

void
acd()
{
    for (c = lo;c <= hi; c++)
        for (d = lo;d <= hi; d++)
            if ((!unique) || (c != d))
                {
                a = c + d;
                if ((a >= lo) && (a <= hi) &&
                   ((!unique) || ((c != 0) && (d != 0))))
                    ge();
                }
}

void
foursquares(int plo,int phi, int punique,int pshow)
{
    lo = plo;
    hi = phi;
    unique = punique;
    show = pshow;
    solutions = 0;

    printf("\n");

    acd();

    if (unique)
        printf("\n%d unique solutions in %d to %d\n",solutions,lo,hi);
    else
        printf("\n%d non-unique solutions in %d to %d\n",solutions,lo,hi);
}

main()
{
    foursquares(1,7,TRUE,TRUE);
    foursquares(3,9,TRUE,TRUE);
    foursquares(0,9,FALSE,FALSE);
}

4 7 1 3 2 6 5
6 4 1 5 2 3 7
3 7 2 1 5 4 6
5 6 2 3 1 7 4
7 3 2 5 1 4 6
4 5 3 1 6 2 7
6 4 5 1 2 7 3
7 2 6 1 3 5 4

8 unique solutions in 1 to 7

7 8 3 4 5 6 9
8 7 3 5 4 6 9
9 6 4 5 3 7 8
9 6 5 4 3 8 7

4 unique solutions in 3 to 9

2860 non-unique solutions in 0 to 9

The code finds all possible solutions for a puzzle where seven variables (a, b, c, d, e, f, g) are replaced with unique decimal digits ranging from a given low to high value. The sum of the variables in each of the four squares must be equal. It provides solutions for the ranges 1-7 and 3-9. Additionally, it calculates the number of solutions when the variables can have non-unique values in the range 0-9.


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>

#define PI 3.14159265
const char * shades = " .:-*ca&#%@";

/* distance of (x, y) from line segment (0, 0)->(x0, y0) */
double dist(double x, double y, double x0, double y0) {
	double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0);

	if (l > 1) {
		x -= x0;
		y -= y0;
	} else if (l >= 0) {
		x -= l * x0;
		y -= l * y0;
	}
	return sqrt(x * x + y * y);
}

enum { sec = 0, min, hur }; // for subscripts

void draw(int size)
{
#	define for_i for(int i = 0; i < size; i++)
#	define for_j for(int j = 0; j < size * 2; j++)

	double angle, cx = size / 2.;
	double sx[3], sy[3], sw[3];
	double fade[] = { 1, .35, .35 }; /* opacity of each arm */
	struct timeval tv;
	struct tm *t;

	/* set width of each arm */
	sw[sec] = size * .02;
	sw[min] = size * .03;
	sw[hur] = size * .05;

every_second:
	gettimeofday(&tv, 0);
	t = localtime(&tv.tv_sec);

	angle = t->tm_sec * PI / 30;
	sy[sec] = -cx * cos(angle);
	sx[sec] =  cx * sin(angle);

	angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI;
	sy[min] = -cx * cos(angle) * .8;
	sx[min] =  cx * sin(angle) * .8;

	angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI;
	sy[hur] = -cx * cos(angle) * .6;
	sx[hur] =  cx * sin(angle) * .6;

	printf("\033[s"); /* save cursor position */
	for_i {
		printf("\033[%d;0H", i);  /* goto row i, col 0 */
		double y = i - cx;
		for_j {
			double x = (j - 2 * cx) / 2;

			int pix = 0;
			/* calcs how far the "pixel" is from each arm and set
			 * shade, with some anti-aliasing.  It's ghetto, but much
			 * easier than a real scanline conversion.
			 */
			for (int k = hur; k >= sec; k--) {
				double d = dist(x, y, sx[k], sy[k]);
				if (d < sw[k] - .5)
					pix = 10 * fade[k];
				else if (d < sw[k] + .5)
					pix = (5 + (sw[k] - d) * 10) * fade[k];
			}
			putchar(shades[pix]);
		}
	}
	printf("\033[u"); /* restore cursor pos so you can bg the job -- value unclear */

	fflush(stdout);
	sleep(1); /* sleep 1 can at times miss a second, but will catch up next update */
	goto every_second;
}

int main(int argc, char *argv[])
{
	int s;
	if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20;
	draw(s);
	return 0;
}

// clockrosetta.c - https://rosettacode.org/wiki/Draw_a_clock

// # Makefile
// CFLAGS = -O3 -Wall -Wfatal-errors -Wpedantic -Werror
// LDLIBS = -lX11 -lXext -lm
// all:  clockrosetta

#define SIZE 500

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <time.h>
#include <X11/extensions/Xdbe.h>
#include <math.h>

static XdbeBackBuffer dbewindow = 0;
static Display *display;
static Window window;
static int needseg = 1;
static double d2r;
static XSegment seg[61];
static GC gc;
static int mw = SIZE / 2;
static int mh = SIZE / 2;

static void
draw(void)
  {
  struct tm *ptm;
  int i;
  double angle;
  double delta;
  int radius = (mw < mh ? mw : mh) - 2;
  XPoint pt[3];
  double onetwenty = 3.1415926 * 2 / 3;
  XdbeSwapInfo swapi;
   time_t newtime;

  if(dbewindow == 0)
    {
    dbewindow = XdbeAllocateBackBufferName(display, window, XdbeBackground);
    XClearWindow(display, window);
    }

  time(&newtime);
  ptm = localtime(&newtime);

  if(needseg)
    {
    d2r = atan2(1.0, 0.0) / 90.0;
    for(i = 0; i < 60; i++)
      {
      angle = (double)i * 6.0 * d2r;
      delta = i % 5 ? 0.97 : 0.9;
      seg[i].x1 = mw + radius * delta * sin(angle);
      seg[i].y1 = mh - radius * delta * cos(angle);
      seg[i].x2 = mw + radius * sin(angle);
      seg[i].y2 = mh - radius * cos(angle);
      }
    needseg = 0;
    }

  angle = (double)(ptm->tm_sec) * 6.0 * d2r;
  seg[60].x1 = mw;
  seg[60].y1 = mh;
  seg[60].x2 = mw + radius * 0.9 * sin(angle);
  seg[60].y2 = mh - radius * 0.9 * cos(angle);
  XDrawSegments(display, dbewindow, gc, seg, 61);

  angle = (double)ptm->tm_min * 6.0 * d2r;
  pt[0].x = mw + radius * 3 / 4 * sin(angle);
  pt[0].y = mh - radius * 3 / 4 * cos(angle);
  pt[1].x = mw + 6 * sin(angle + onetwenty);
  pt[1].y = mh - 6 * cos(angle + onetwenty);
  pt[2].x = mw + 6 * sin(angle - onetwenty);
  pt[2].y = mh - 6 * cos(angle - onetwenty);
  XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);

  angle = (double)(ptm->tm_hour * 60 + ptm->tm_min) / 2.0 * d2r;
  pt[0].x = mw + radius / 2 * sin(angle);
  pt[0].y = mh - radius / 2 * cos(angle);
  pt[1].x = mw + 6 * sin(angle + onetwenty);
  pt[1].y = mh - 6 * cos(angle + onetwenty);
  pt[2].x = mw + 6 * sin(angle - onetwenty);
  pt[2].y = mh - 6 * cos(angle - onetwenty);
  XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);

  swapi.swap_window = window;
  swapi.swap_action = XdbeBackground;
  XdbeSwapBuffers(display, &swapi, 1);
  }

int
main(int argc, char *argv[])
  {
  Atom wm_both_protocols[1];
  Atom wm_delete;
  Atom wm_protocols;
  Window root;
  XEvent event;
  XSetWindowAttributes attr;
  fd_set fd;
  int exposed = 0;
  int more = 1;
  struct timeval tv;

  display = XOpenDisplay(NULL);

  if(display == NULL)
    {
    fprintf(stderr,"Error: The display cannot be opened\n");
    exit(1);
    }

  root = DefaultRootWindow(display);
  wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False);
  wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False);

  attr.background_pixel = 0x000000;
  attr.event_mask = KeyPress | KeyRelease |
    ButtonPressMask | ButtonReleaseMask | ExposureMask;

  window = XCreateWindow(display, root,
    0, 0, SIZE, SIZE, 0,
    CopyFromParent, InputOutput, CopyFromParent,
    CWBackPixel | CWEventMask,
    &attr
    );

  XStoreName(display, window, "Clock for RosettaCode");

  wm_both_protocols[0] = wm_delete;
  XSetWMProtocols(display, window, wm_both_protocols, 1);

  gc = XCreateGC(display, window, 0, NULL);
  XSetForeground(display, gc, 0xFFFF80);

  XMapWindow(display, window);

  while(more)
    {
    if(QLength(display) > 0)
      {
      XNextEvent(display, &event);
      }
    else
      {
      int maxfd = ConnectionNumber(display);

      XFlush(display);
      FD_ZERO(&fd);
      FD_SET(ConnectionNumber(display), &fd);

      event.type = LASTEvent;
      tv.tv_sec = 0;
      tv.tv_usec = 250000;
      if(select(maxfd + 1, &fd, NULL, NULL, &tv) > 0)
        {
        if(FD_ISSET(ConnectionNumber(display), &fd))
          {
          XNextEvent(display, &event);
          }
        }
      }

    switch(event.type)
      {
    case Expose:
      exposed = 1;
      draw();
      break;

    case ButtonRelease:
    case KeyRelease:
      more = 0;
    case ButtonPress:  // ignore
    case KeyPress:     // ignore
      break;

    case LASTEvent:  // the timeout comes here
      if(exposed) draw();
      break;

    case ConfigureNotify:
      mw = event.xconfigure.width / 2;
      mh = event.xconfigure.height / 2;
      needseg = 1;
      break;

    case ClientMessage: // for close request from WM
      if(event.xclient.window == window &&
        event.xclient.message_type == wm_protocols &&
        event.xclient.format == 32 &&
        event.xclient.data.l[0] == wm_delete)
        {
        more = 0;
        }
      break;

//    default:
//      printf("unexpected event.type %d\n", event.type);;
      }
    }

  XCloseDisplay(display);
  exit(0);
  }

// END

draw a simple, time-keeping device that updates every second. It does not need to be hyper-accurate but should be in sync with the system clock. The code avoids unnecessary system resource usage and maintains simplicity and clarity. It can be a text-based or graphical representation, but not a string of numbers. The code is written in C99 and compiled with gcc -std=c99.


tcc -DSTRUCT=struct -DCONST=const -DINT=int -DCHAR=char -DVOID=void -DMAIN=main -DIF=if -DELSE=else -DWHILE=while -DFOR=for -DDO=do -DBREAK=break -DRETURN=return -DPUTCHAR=putchar UCCALENDAR.c

/* UPPER CASE ONLY VERSION OF THE ORIGINAL CALENDAR.C, CHANGES MOSTLY TO AVOID NEEDING #INCLUDES */
/* ERROR MESSAGES GO TO STDOUT TO SLIGHTLY SIMPLIFY THE I/O HANDLING                             */
/* WHEN COMPILING THIS, THE COMMAND LINE SHOULD SPECIFY -D OPTIONS FOR THE FOLLOWING WORDS:      */
/*    STRUCT, VOID, INT, CHAR, CONST, MAIN, IF, ELSE, WHILE, FOR, DO, BREAK, RETURN, PUTCHAR     */
/* THE VALUE OF EACH MACRO SHOULD BE THE WORD IN LOWER-CASE                                      */

INT PUTCHAR(INT);

INT WIDTH = 80, YEAR = 1969;
INT COLS, LEAD, GAP;

CONST CHAR *WDAYS[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
STRUCT MONTHS {
    CONST CHAR *NAME;
    INT DAYS, START_WDAY, AT;
} MONTHS[12] = {
    { "JANUARY",    31, 0, 0 },
    { "FEBRUARY",    28, 0, 0 },
    { "MARCH",    31, 0, 0 },
    { "APRIL",    30, 0, 0 },
    { "MAY",    31, 0, 0 },
    { "JUNE",    30, 0, 0 },
    { "JULY",    31, 0, 0 },
    { "AUGUST",    31, 0, 0 },
    { "SEPTEMBER",    30, 0, 0 },
    { "OCTOBER",    31, 0, 0 },
    { "NOVEMBER",    30, 0, 0 },
    { "DECEMBER",    31, 0, 0 }
};

VOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }
VOID PRINT(CONST CHAR * S){ WHILE (*S != '\0') { PUTCHAR(*S++); } }
INT  STRLEN(CONST CHAR * S)
{
   INT L = 0;
   WHILE (*S++ != '\0') { L ++; };
RETURN L;
}
INT ATOI(CONST CHAR * S)
{
    INT I = 0;
    INT SIGN = 1;
    CHAR C;
    WHILE ((C = *S++) != '\0') {
        IF (C == '-')
            SIGN *= -1;
        ELSE {
            I *= 10;
            I += (C - '0');
        }
    }
RETURN I * SIGN;
}

VOID INIT_MONTHS(VOID)
{
    INT I;

    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))
        MONTHS[1].DAYS = 29;

    YEAR--;
    MONTHS[0].START_WDAY
        = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;

    FOR (I = 1; I < 12; I++)
        MONTHS[I].START_WDAY =
            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;

    COLS = (WIDTH + 2) / 22;
    WHILE (12 % COLS) COLS--;
    GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;
    IF (GAP > 4) GAP = 4;
    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;
        YEAR++;
}

VOID PRINT_ROW(INT ROW)
{
    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;
    SPACE(LEAD);
    FOR (C = FROM; C < TO; C++) {
        I = STRLEN(MONTHS[C].NAME);
        SPACE((20 - I)/2);
        PRINT(MONTHS[C].NAME);
        SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));
    }
    PUTCHAR('\012');

    SPACE(LEAD);
    FOR (C = FROM; C < TO; C++) {
        FOR (I = 0; I < 7; I++) {
            PRINT(WDAYS[I]);
            PRINT(I == 6 ? "" : " ");
        }
        IF (C < TO - 1) SPACE(GAP);
        ELSE PUTCHAR('\012');
    }

    WHILE (1) {
        FOR (C = FROM; C < TO; C++)
            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;
        IF (C == TO) BREAK;

        SPACE(LEAD);
        FOR (C = FROM; C < TO; C++) {
            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);
            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {
                INT MM = ++MONTHS[C].AT;
                PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));
                PUTCHAR('0' + (MM %10));
                IF (I < 7 || C < TO - 1) PUTCHAR(' ');
            }
            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);
            IF (C < TO - 1) SPACE(GAP - 1);
            MONTHS[C].START_WDAY = 0;
        }
        PUTCHAR('\012');
    }
    PUTCHAR('\012');
}

VOID PRINT_YEAR(VOID)
{
    INT Y = YEAR;
    INT ROW;
    CHAR BUF[32];
    CHAR * B = &(BUF[31]);
    *B-- = '\0';
    DO {
        *B-- = '0' + (Y % 10);
        Y /= 10;
    } WHILE (Y > 0);
    B++;
    SPACE((WIDTH - STRLEN(B)) / 2);
    PRINT(B);PUTCHAR('\012');PUTCHAR('\012');
    FOR (ROW = 0; ROW * COLS < 12; ROW++)
        PRINT_ROW(ROW);
}

INT MAIN(INT C, CHAR **V)
{
    INT I, YEAR_SET = 0, RESULT = 0;
    FOR (I = 1; I < C && RESULT == 0; I++) {
        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\0') {
            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)
                RESULT = 1;
        } ELSE IF (!YEAR_SET) {
            YEAR = ATOI(V[I]);
            IF (YEAR <= 0)
                YEAR = 1969;
            YEAR_SET = 1;
        } ELSE
            RESULT = 1;
    }

    IF (RESULT == 0) {
        INIT_MONTHS();
        PRINT_YEAR();
    } ELSE {
        PRINT("BAD ARGS\012USAGE: ");
        PRINT(V[0]);
        PRINT(" YEAR [-W WIDTH (>= 20)]\012");
    }
RETURN RESULT;
}

The code provides an algorithm for a calendar task, formatted to fit a 132-character wide page, inspired by 1969 era line printers. The entire code is written in uppercase, as per the requirements of some 1960s computer systems. The code does not include Snoopy generation but outputs a placeholder instead. The code is designed to be compatible with UNIX systems connected to upper-case only terminals, and can be compiled with most C compilers.


#include <stdio.h>
#include <stdlib.h>

typedef unsigned long long xint;
typedef unsigned long ulong;

inline ulong gcd(ulong m, ulong n)
{
    ulong t;
    while (n) { t = n; n = m % n; m = t; }
    return m;
}

int main()
{
    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;
    xint aa, bb, cc;

    for (a = 1; a <= max_p / 3; a++) {
        aa = (xint)a * a;
        printf("a = %lu\r", a); /* show that we are working */
        fflush(stdout);

        /*  max_p/2: valid limit, because one side of triangle
         *  must be less than the sum of the other two
         */
        for (b = a + 1; b < max_p/2; b++) {
            bb = (xint)b * b;
            for (c = b + 1; c < max_p/2; c++) {
                cc = (xint)c * c;
                if (aa + bb < cc) break;
                if (a + b + c > max_p) break;

                if (aa + bb == cc) {
                    pytha++;
                    if (gcd(a, b) == 1) prim++;
                }
            }
        }
    }

    printf("Up to %lu, there are %lu triples, of which %lu are primitive\n",
        max_p, pytha, prim);

    return 0;
}
output:Up to 100, there are 17 triples, of which 7 are primitive

Efficient method, generating primitive triples only as described in the same WP article:#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/* should be 64-bit integers if going over 1 billion */
typedef unsigned long xint;
#define FMT "%lu"

xint total, prim, max_peri;
xint U[][9] =  {{ 1, -2, 2,  2, -1, 2,  2, -2, 3},
        { 1,  2, 2,  2,  1, 2,  2,  2, 3},
        {-1,  2, 2, -2,  1, 2, -2,  2, 3}};

void new_tri(xint in[])
{
    int i;
    xint t[3], p = in[0] + in[1] + in[2];

    if (p > max_peri) return;

    prim ++;

    /* for every primitive triangle, its multiples would be right-angled too;
     * count them up to the max perimeter */
    total += max_peri / p;

    /* recursively produce next tier by multiplying the matrices */
    for (i = 0; i < 3; i++) {
        t[0] = U[i][0] * in[0] + U[i][1] * in[1] + U[i][2] * in[2];
        t[1] = U[i][3] * in[0] + U[i][4] * in[1] + U[i][5] * in[2];
        t[2] = U[i][6] * in[0] + U[i][7] * in[1] + U[i][8] * in[2];
        new_tri(t);
    }
}

int main()
{
    xint seed[3] = {3, 4, 5};

    for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) {
        total = prim = 0;
        new_tri(seed);

        printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n",
            max_peri, total, prim);
    }
    return 0;
}
OutputUp to 10: 0 triples, 0 primitives.
Up to 100: 17 triples, 7 primitives.
Up to 1000: 325 triples, 70 primitives.
Up to 10000: 4858 triples, 703 primitives.
Up to 100000: 64741 triples, 7026 primitives.
Up to 1000000: 808950 triples, 70229 primitives.
Up to 10000000: 9706567 triples, 702309 primitives.
Up to 100000000: 113236940 triples, 7023027 primitives.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/* should be 64-bit integers if going over 1 billion */
typedef unsigned long xint;
#define FMT "%lu"

xint total, prim, max_peri;

void new_tri(xint in[])
{
    int i;
    xint t[3], p;
    xint x = in[0], y = in[1], z = in[2];

recur:  p = x + y + z;
    if (p > max_peri) return;

    prim ++;
    total += max_peri / p;

    t[0] = x - 2 * y + 2 * z;
    t[1] = 2 * x - y + 2 * z;
    t[2] = t[1] - y + z;
    new_tri(t);

    t[0] += 4 * y;
    t[1] += 2 * y;
    t[2] += 4 * y;
    new_tri(t);

    z = t[2] - 4 * x;
    y = t[1] - 4 * x;
    x = t[0] - 2 * x;
    goto recur;
}

int main()
{
    xint seed[3] = {3, 4, 5};

    for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) {
        total = prim = 0;
        new_tri(seed);

        printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n",
            max_peri, total, prim);
    }
    return 0;
}

The code calculates the number of Pythagorean triples (sets of three positive integers a, b, c where a^2 + b^2 = c^2 and a < b < c) with a perimeter no larger than 100, and also determines how many of these triples are primitive (where a, b, and c are co-prime). The code is also designed to handle larger perimeters up to 100,000,000.


Works with: ANSI C version C89
Library: SDL
Uses: SDL (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/SDL/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
Uses: ANSI C (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/ANSI C/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

/*
 *   Opens an 800x600 16bit color window.
 *   Done here with ANSI C.
 */

#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"

int main()
{
  SDL_Surface *screen;

  if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
    return 1;
  }
  atexit(SDL_Quit);
  screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );

  return 0;
}

Library: GTK
Uses: GTK (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/GTK/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

#include <gtk/gtk.h>

int
main(int argc, char *argv[])
{
  GtkWidget *window;

  gtk_init(&argc, &argv);
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_signal_connect(GTK_OBJECT(window), "destroy",
    GTK_SIGNAL_FUNC(gtk_main_quit), NULL);
  gtk_widget_show(window);
  gtk_main();

  return 0;
}

Library: Gtk2
Uses: Gtk2 (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/Gtk2/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

#include <gtk/gtk.h>

int
main(int argc, char *argv[])
{
  GtkWidget *window;

  gtk_init(&argc, &argv);
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect (window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  gtk_widget_show(window);
  gtk_main();

  return 0;
}

Library: GLUT
Uses: GLUT (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/GLUT/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

// A C+GLUT implementation of the Creating a Window task at Rosetta Code
// http://rosettacode.org/wiki/Creating_a_Window
#include <stdlib.h>
#include <GL/glut.h>

// This function is not strictly necessary to meet the requirements of the task.
void onKeyPress(unsigned char key, int x, int y)
{
	// If you have any cleanup or such, you need to use C's
	// onexit routine for registering cleanup callbacks.
	exit(0);

}

int main(int argc, char **argv)
{
	// Pulls out any command-line arguments that are specific to GLUT,
	// And leaves a command-line argument set without any of those arguments
	// when it returns.
	// (If you want a copy, take a copy first.)
	glutInit(&argc, argv);

	// Tell GLUT we want to create a window.
	// It won't *actually* be created until we call glutMainLoop below.
	glutCreateWindow("Goodbye, World!");

	// Register a callback to handle key press events (so we can quit on
	// when someone hits a key)  This part is not necessary to meet the
	// requirements of the task.
	glutKeyboardFunc(&onKeyPress);

	// Put the execution of the app in glut's hands. Most GUI environments
	// involve a message loop that communicate window events. GLUT handles
	// most of these with defaults, except for any we register callbacks
	// for. (Like the onKeyPress above.)
	glutMainLoop();

	return 0;

}

The code creates a GUI window that responds to close requests. It doesn't contain any content or drawing callbacks, resulting in a blank appearance. A keypress callback is registered for closing the program. The code is compiled using different commands for SDL, GTK, and GLUT libraries.


/* declare array */
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");

/* init the freq table: */
for (ch = 0; ch < 26; ch++)
    frequency[ch] = 0;

while (1) {
    ch = fgetc(txt_file);
    if (ch == EOF) break; /* end of file or read error.  EOF is typically -1 */

    /* assuming ASCII; "letters" means "a to z" */
    if ('a' <= ch && ch <= 'z')      /* lower case */
        frequency[ch-'a']++;
    else if ('A' <= ch && ch <= 'Z') /* upper case */
        frequency[ch-'A']++;
}

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


struct link {
  struct link *next;
  int data;
};

define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.


Library: SDL
Library: SGE or Library: cairo
#include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif

#define SIZE           800   // determines size of window
#define SCALE          5     // determines how quickly branches shrink (higher value means faster shrinking)
#define BRANCHES       14    // number of branches
#define ROTATION_SCALE 0.75  // determines how slowly the angle between branches shrinks (higher value means slower shrinking)
#define INITIAL_LENGTH 50    // length of first branch

double rand_fl(){
  return (double)rand() / (double)RAND_MAX;
}

void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
               double directionx, double directiony, double size,
               double rotation, int depth) {
#ifdef WITH_CAIRO
  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
                                                               CAIRO_FORMAT_RGB24,
							       surface->w, surface->h,
							       surface->pitch );
  cairo_t *ct = cairo_create(surf);

  cairo_set_line_width(ct, 1);
  cairo_set_source_rgba(ct, 0,0,0,1);
  cairo_move_to(ct, (int)offsetx, (int)offsety);
  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
  cairo_stroke(ct);
#else
  sge_AALine(surface,
      (int)offsetx, (int)offsety,
      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),
      SDL_MapRGB(surface->format, 0, 0, 0));
#endif
  if (depth > 0){
    // draw left branch
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(rotation) + directiony * sin(rotation),
        directionx * -sin(rotation) + directiony * cos(rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);

    // draw right branch
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(-rotation) + directiony * sin(-rotation),
        directionx * -sin(-rotation) + directiony * cos(-rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
  }
}

void render(SDL_Surface * surface){
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
  draw_tree(surface,
      surface->w / 2.0,
      surface->h - 10.0,
      0.0, -1.0,
      INITIAL_LENGTH,
      PI / 8,
      BRANCHES);
  SDL_UpdateRect(surface, 0, 0, 0, 0);
}

int main(){
  SDL_Surface * screen;
  SDL_Event evt;

  SDL_Init(SDL_INIT_VIDEO);

  srand((unsigned)time(NULL));

  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);

  render(screen);
  while(1){
    if (SDL_PollEvent(&evt)){
      if(evt.type == SDL_QUIT) break;
    }
    SDL_Delay(1);
  }
  SDL_Quit();
  return 0;
}

generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.