WeixiangYan/CodeTransOcean huggingface dataset:
Task: Factorions

C: #include <stdio.h>

int main() {    
    int n, b, d;
    unsigned long long i, j, sum, fact[12];
    
    fact[0] = 1;
    for (n = 1; n < 12; ++n) {
        fact[n] = fact[n-1] * n;
    }

    for (b = 9; b <= 12; ++b) {
        printf("The factorions for base %d are:\n", b);
        for (i = 1; i < 1500000; ++i) {
            sum = 0;
            j = i;
            while (j > 0) {
                d = j % b;
                sum += fact[d];
                j /= b;
            }
            if (sum == i) printf("%llu ", i);
        }
        printf("\n\n");
    }
    return 0;
}




Go: package main

import (
    "fmt"
    "strconv"
)

func main() {
    
    var fact [12]uint64
    fact[0] = 1
    for n := uint64(1); n < 12; n++ {
        fact[n] = fact[n-1] * n
    }

    for b := 9; b <= 12; b++ {
        fmt.Printf("The factorions for base %d are:\n", b)
        for i := uint64(1); i < 1500000; i++ {
            digits := strconv.FormatUint(i, b)
            sum := uint64(0)
            for _, digit := range digits {
                if digit < 'a' {
                    sum += fact[digit-'0']
                } else {
                    sum += fact[digit+10-'a']
                }
            }
            if sum == i {
                fmt.Printf("%d ", i)
            }
        }
        fmt.Println("\n")
    }
}
Task: Additive primes

C: #include <stdbool.h>
#include <stdio.h>
#include <string.h>

void memoizeIsPrime( bool * result, const int N )
{
    result[2] = true;
    result[3] = true;
    int prime[N];
    prime[0] = 3;
    int end = 1;
    for (int n = 5; n < N; n += 2)
    {
        bool n_is_prime = true;
        for (int i = 0; i < end; ++i)
        {
            const int PRIME = prime[i];
            if (n % PRIME == 0)
            {
                n_is_prime = false;
                break;
            }
            if (PRIME * PRIME > n)
            {
                break;
            }
        }
        if (n_is_prime)
        {
            prime[end++] = n;
            result[n] = true;
        }
    }
}

int sumOfDecimalDigits( int n )
{
    int sum = 0;
    while (n > 0)
    {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main( void )
{
    const int N = 500;

    printf( "Rosetta Code: additive primes less than %d:\n", N );

    bool is_prime[N];
    memset( is_prime, 0, sizeof(is_prime) );
    memoizeIsPrime( is_prime, N );

    printf( "   2" );
    int count = 1;
    for (int i = 3; i < N; i += 2)
    {
        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])
        {
            printf( "%4d", i );
            ++count;
            if ((count % 10) == 0)
            {
                printf( "\n" );
            }
        }
    }
    printf( "\nThose were %d additive primes.\n", count );
    return 0;
}




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func sumDigits(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func main() {
    fmt.Println("Additive primes less than 500:")
    i := 2
    count := 0
    for {
        if isPrime(i) && isPrime(sumDigits(i)) {
            count++
            fmt.Printf("%3d  ", i)
            if count%10 == 0 {
                fmt.Println()
            }
        }
        if i > 2 {
            i += 2
        } else {
            i++
        }
        if i > 499 {
            break
        }
    }
    fmt.Printf("\n\n%d additive primes found.\n", count)
}
Task: Inverted syntax

C: #include <stdio.h>
#include <stdlib.h>
#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:
#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)


int foo() { return 1; }

main()
{
        int a = 0;

        otherwise  a = 4 given (foo());
        printf("%d\n", a);
        exit(0);
}




Go: package main

import "fmt"

type ibool bool

const itrue ibool = true

func (ib ibool) iif(cond bool) bool {
    if cond {
        return bool(ib)
    }
    return bool(!ib)
}

func main() {
    var needUmbrella bool
    raining := true

    
    if raining {
        needUmbrella = true
    }
    fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)

    
    raining = false
    needUmbrella = itrue.iif(raining)
    fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
Task: Perfect totient numbers

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

long totient(long n){
	long tot = n,i;
	
	for(i=2;i*i<=n;i+=2){
		if(n%i==0){
			while(n%i==0)
				n/=i;
			tot-=tot/i;
		}
		
		if(i==2)
			i=1;
	}
	
	if(n>1)
		tot-=tot/n;
	
	return tot;
}

long* perfectTotients(long n){
	long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;
	
	for(m=1;count<n;m++){
		 tot = m;
		 sum = 0;
        while(tot != 1){
            tot = totient(tot);
            sum += tot;
        }
        if(sum == m)
			ptList[count++] = m;
        }
		
		return ptList;
}

long main(long argC, char* argV[])
{
	long *ptList,i,n;
	
	if(argC!=2)
		printf("Usage : %s <number of perfect Totient numbers required>",argV[0]);
	else{
		n = atoi(argV[1]);
		
		ptList = perfectTotients(n);
		
		printf("The first %d perfect Totient numbers are : \n[",n);
		
		for(i=0;i<n;i++)
			printf(" %d,",ptList[i]);
		printf("\b]");
	}
	
	return 0;
}




Go: package main

import "fmt"

func gcd(n, k int) int {
    if n < k || k < 1 {
        panic("Need n >= k and k >= 1")
    }

    s := 1
    for n&1 == 0 && k&1 == 0 {
        n >>= 1
        k >>= 1
        s <<= 1
    }

    t := n
    if n&1 != 0 {
        t = -k
    }
    for t != 0 {
        for t&1 == 0 {
            t >>= 1
        }
        if t > 0 {
            n = t
        } else {
            k = -t
        }
        t = n - k
    }
    return n * s
}

func totient(n int) int {
    tot := 0
    for k := 1; k <= n; k++ {
        if gcd(n, k) == 1 {
            tot++
        }
    }
    return tot
}

func main() {
    var perfect []int
    for n := 1; len(perfect) < 20; n += 2 {
        tot := n
        sum := 0
        for tot != 1 {
            tot = totient(tot)
            sum += tot
        }
        if sum == n {
            perfect = append(perfect, n)
        }
    }
    fmt.Println("The first 20 perfect totient numbers are:")
    fmt.Println(perfect)
}
Task: Delegates

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef const char * (*Responder)( int p1);

typedef struct sDelegate {
    Responder operation;
} *Delegate;


Delegate NewDelegate( Responder rspndr )
{
    Delegate dl = malloc(sizeof(struct sDelegate));
    dl->operation = rspndr;
    return dl;
}


const char *DelegateThing(Delegate dl, int p1)
{
    return  (dl->operation)? (*dl->operation)(p1) : NULL;
}


typedef struct sDelegator {
    int     param;
    char    *phrase;
    Delegate delegate;
} *Delegator;

const char * defaultResponse( int p1)
{
    return "default implementation";
}

static struct sDelegate defaultDel = { &defaultResponse };


Delegator NewDelegator( int p, char *phrase)
{
    Delegator d  = malloc(sizeof(struct sDelegator));
    d->param = p;
    d->phrase = phrase;
    d->delegate = &defaultDel;	
    return d;
}


const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
    const char *rtn;
    if (delroy) {
        rtn = DelegateThing(delroy, p1);
        if (!rtn) {			
            rtn = DelegateThing(theDelegator->delegate, p1);
        }
    }
    else 		
        rtn = DelegateThing(theDelegator->delegate, p1);

    printf("%s\n", theDelegator->phrase );
    return rtn;
}


const char *thing1( int p1)
{
    printf("We're in thing1 with value %d\n" , p1);
    return "delegate implementation";
}

int main()
{
    Delegate del1 = NewDelegate(&thing1);
    Delegate del2 = NewDelegate(NULL);
    Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");

    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, NULL));
    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, del1));
    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, del2));
    return 0;
}




Go: package main
import "fmt"

type Delegator struct {
    delegate interface{} 
}


type Thingable interface {
    thing() string
}

func (self Delegator) operation() string {
    if v, ok := self.delegate.(Thingable); ok {
        return v.thing()
    }
    return "default implementation"
}

type Delegate int 

func (Delegate) thing() string {
    return "delegate implementation"
}

func main() {
    
    a := Delegator{}
    fmt.Println(a.operation()) 

    
    a.delegate = "A delegate may be any object"
    fmt.Println(a.operation()) 

    
    var d Delegate
    a.delegate = d
    fmt.Println(a.operation()) 
}
Task: Sum of divisors

C: #include <stdio.h>


unsigned int divisor_sum(unsigned int n) {
    unsigned int total = 1, power = 2;
    unsigned int p;
    
    for (; (n & 1) == 0; power <<= 1, n >>= 1) {
        total += power;
    }
    
    for (p = 3; p * p <= n; p += 2) {
        unsigned int sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p) {
            sum += power;
        }
        total *= sum;
    }
    
    if (n > 1) {
        total *= n + 1;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int n;
    printf("Sum of divisors for the first %d positive integers:\n", limit);
    for (n = 1; n <= limit; ++n) {
        printf("%4d", divisor_sum(n));
        if (n % 10 == 0) {
            printf("\n");
        }
    }
    return 0;
}




Go: package main

import "fmt"

func sumDivisors(n int) int {
    sum := 0
    i := 1
    k := 2
    if n%2 == 0 {
        k = 1
    }
    for i*i <= n {
        if n%i == 0 {
            sum += i
            j := n / i
            if j != i {
                sum += j
            }
        }
        i += k
    }
    return sum
}

func main() {
    fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
    for i := 1; i <= 100; i++ {
        fmt.Printf("%3d   ", sumDivisors(i))
        if i%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Enforced immutability

C: #define PI      3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100




Go: package main

func main() {
    s := "immutable"
    s[0] = 'a'
}
Task: Spiral matrix

C: #include <stdio.h>
#include <stdlib.h>
 
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
	int i, j, m = 0, n = 0;
 
	
	if (c >= 2) m = atoi(v[1]);
	if (c >= 3) n = atoi(v[2]);
	if (m <= 0) m = 5;
	if (n <= 0) n = m;
 
	int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
	s[0] = (int*)(s + m);
	for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
 
	int dx = 1, dy = 0, val = 0, t;
	for (i = j = 0; valid(i, j); i += dy, j += dx ) {
		for (; valid(i, j); j += dx, i += dy)
			s[i][j] = ++val;
 
		j -= dx; i -= dy;
		t = dy; dy = dx; dx = -t;
	}

	for (t = 2; val /= 10; t++);

	for(i = 0; i < m; i++)
		for(j = 0; j < n || !putchar('\n'); j++)
			printf("%*d", t, s[i][j]);

	return 0;
}




Go: package main

import (
    "fmt"
    "strconv"
)

var n = 5

func main() {
    if n < 1 {
        return
    }
    top, left, bottom, right := 0, 0, n-1, n-1
    sz := n * n
    a := make([]int, sz)
    i := 0
    for left < right {
        
        for c := left; c <= right; c++ {
            a[top*n+c] = i
            i++
        }
        top++
        
        for r := top; r <= bottom; r++ {
            a[r*n+right] = i
            i++
        }
        right--
        if top == bottom {
            break
        }
        
        for c := right; c >= left; c-- {
            a[bottom*n+c] = i
            i++
        }
        bottom--
        
        for r := bottom; r >= top; r-- {
            a[r*n+left] = i
            i++
        }
        left++
    }
    
    a[top*n+left] = i

    
    w := len(strconv.Itoa(n*n - 1))
    for i, e := range a {
        fmt.Printf("%*d ", w, e)
        if i%n == n-1 {
            fmt.Println("")
        }
    }
}
Task: Call a foreign-language function

C: 



#include <stdio.h>

void sayHello(char* name){
    printf("Hello %s!\n", name);
}

int doubleNum(int num){
    return num * 2;
}




Go: package main



import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    
    go1 := "hello C"
    
    c1 := C.CString(go1)
    
    go1 = ""
    
    c2 := C.strdup(c1)
    
    C.free(unsafe.Pointer(c1))
    
    go2 := C.GoString(c2)
    
    C.free(unsafe.Pointer(c2))
    
    fmt.Println(go2)
}
Task: Knuth's algorithm S

C: #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

struct s_env {
    unsigned int n, i;
    size_t size;
    void *sample;
};

void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
    s_env->i = 0;
    s_env->n = n;
    s_env->size = size;
    s_env->sample = malloc(n * size);
}

void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
    memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}

void *s_of_n(struct s_env *s_env, void *item)
{
    s_env->i++;
    if (s_env->i <= s_env->n)
        sample_set_i(s_env, s_env->i - 1, item);
    else if ((rand() % s_env->i) < s_env->n)
        sample_set_i(s_env, rand() % s_env->n, item);
    return s_env->sample;
}

int *test(unsigned int n, int *items_set, unsigned int num_items)
{
    int i;
    struct s_env s_env;
    s_of_n_init(&s_env, sizeof(items_set[0]), n);
    for (i = 0; i < num_items; i++) {
        s_of_n(&s_env, (void *) &items_set[i]);
    }
    return (int *)s_env.sample;
}

int main()
{
    unsigned int i, j;
    unsigned int n = 3;
    unsigned int num_items = 10;
    unsigned int *frequencies;
    int *items_set;
    srand(time(NULL));
    items_set = malloc(num_items * sizeof(int));
    frequencies = malloc(num_items * sizeof(int));
    for (i = 0; i < num_items; i++) {
        items_set[i] = i;
        frequencies[i] = 0;
    }
    for (i = 0; i < 100000; i++) {
        int *res = test(n, items_set, num_items);
        for (j = 0; j < n; j++) {
            frequencies[res[j]]++;
        }
	free(res);
    }
    for (i = 0; i < num_items; i++) {
        printf(" %d", frequencies[i]);
    }
    puts("");
    return 0;
}




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}
Task: Command-line arguments

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

int main(int argc, char* argv[])
{
  int i;
  (void) printf("This program is named %s.\n", argv[0]);
  for (i = 1; i < argc; ++i)
    (void) printf("the argument #%d is %s\n", i, argv[i]);
  return EXIT_SUCCESS;
}




Go: package main
import (
	"fmt"
	"os"
)

func main() {
	for i, x := range os.Args[1:] {
		fmt.Printf("the argument #%d is %s\n", i, x)
	}
}
Task: Array concatenation

C: #include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *array_concat(const void *a, size_t an,
                   const void *b, size_t bn, size_t s)
{
  char *p = malloc(s * (an + bn));
  memcpy(p, a, an*s);
  memcpy(p + an*s, b, bn*s);
  return p;
}


const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };

int main(void)
{
  unsigned int i;

  int *c = ARRAY_CONCAT(int, a, 5, b, 5);

  for(i = 0; i < 10; i++)
    printf("%d\n", c[i]);

  free(c);
  return EXIT_SUCCCESS;
}




Go: package main

import "fmt"

func main() {
    
    
    a := []int{1, 2, 3}
    b := []int{7, 12, 60} 
    c := append(a, b...)
    fmt.Println(c)

    
    
    
    i := []interface{}{1, 2, 3}
    j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
    k := append(i, j...) 
    fmt.Println(k)

    
    
    
    
    
    
    
    l := [...]int{1, 2, 3}
    m := [...]int{7, 12, 60} 
    var n [len(l) + len(m)]int
    copy(n[:], l[:]) 
    copy(n[len(l):], m[:])
    fmt.Println(n)

}
Task: User input_Text

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

int main(void)
{
    
    char str[BUFSIZ];
    puts("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    
    long num;
    char buf[BUFSIZ];
    do
    {
        puts("Enter 75000: ");
        fgets(buf, sizeof(buf), stdin);
        num = strtol(buf, NULL, 10);
    } while (num != 75000);

    return EXIT_SUCCESS;
}




Go: package main

import "fmt"

func main() {
    var s string
    var i int
    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
        fmt.Println("good")
    } else {
        fmt.Println("wrong")
    }
}
Task: Musical scale

C: #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>

typedef struct{
	char str[3];
	int key;
	}note;
	
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};

int main(void)
{
	int i=0;
	
	while(!kbhit())
	{
		printf("\t%s",sequence[i].str);
		sound(261.63*pow(2,sequence[i].key/12.0));
		delay(sequence[i].key%12==0?500:1000);
		i = (i+1)%8;
		i==0?printf("\n"):printf("");
	}
	nosound();
	return 0;
}




Go: package main

import (
    "encoding/binary"
    "log"
    "math"
    "os"
    "strings"
)

func main() {
    const (
        sampleRate = 44100
        duration   = 8
        dataLength = sampleRate * duration
        hdrSize    = 44
        fileLen    = dataLength + hdrSize - 8
    )

    
    buf1 := make([]byte, 1)
    buf2 := make([]byte, 2)
    buf4 := make([]byte, 4)

    
    var sb strings.Builder
    sb.WriteString("RIFF")
    binary.LittleEndian.PutUint32(buf4, fileLen)
    sb.Write(buf4) 
    sb.WriteString("WAVE")
    sb.WriteString("fmt ")
    binary.LittleEndian.PutUint32(buf4, 16)
    sb.Write(buf4) 
    binary.LittleEndian.PutUint16(buf2, 1)
    sb.Write(buf2) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint32(buf4, sampleRate)
    sb.Write(buf4) 
    sb.Write(buf4) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint16(buf2, 8)
    sb.Write(buf2) 
    sb.WriteString("data")
    binary.LittleEndian.PutUint32(buf4, dataLength)
    sb.Write(buf4) 
    wavhdr := []byte(sb.String())

    
    f, err := os.Create("notes.wav")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    f.Write(wavhdr)

    
    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
    for j := 0; j < duration; j++ {
        freq := freqs[j]
        omega := 2 * math.Pi * freq
        for i := 0; i < dataLength/duration; i++ {
            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
            buf1[0] = byte(math.Round(y))
            f.Write(buf1)
        }
    }
}
Task: Cartesian product of two or more lists

C: #include<string.h>
#include<stdlib.h>
#include<stdio.h>

void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
	int i,j;
	
	if(times==numSets){
		printf("(");
		for(i=0;i<times;i++){
			printf("%d,",currentSet[i]);
		}
		printf("\b),");
	}
	else{
		for(j=0;j<setLengths[times];j++){
			currentSet[times] = sets[times][j];
			cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
		}
	}
}

void printSets(int** sets, int* setLengths, int numSets){
	int i,j;
	
	printf("\nNumber of sets : %d",numSets);
	
	for(i=0;i<numSets+1;i++){
		printf("\nSet %d : ",i+1);
		for(j=0;j<setLengths[i];j++){
			printf(" %d ",sets[i][j]);
		}
	}
}

void processInputString(char* str){
	int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
	char *token,*holder,*holderToken;
	
	for(i=0;str[i]!=00;i++)
		if(str[i]=='x')
			numSets++;
		
	if(numSets==0){
			printf("\n%s",str);
			return;
	}
		
	currentSet = (int*)calloc(sizeof(int),numSets + 1);
	
	setLengths = (int*)calloc(sizeof(int),numSets + 1);
	
	sets = (int**)malloc((numSets + 1)*sizeof(int*));
	
	token = strtok(str,"x");
	
	while(token!=NULL){
		holder = (char*)malloc(strlen(token)*sizeof(char));
		
		j = 0;
		
		for(i=0;token[i]!=00;i++){
			if(token[i]>='0' && token[i]<='9')
				holder[j++] = token[i];
			else if(token[i]==',')
				holder[j++] = ' ';
		}
		holder[j] = 00;
		
		setLength = 0;
		
		for(i=0;holder[i]!=00;i++)
			if(holder[i]==' ')
				setLength++;
			
		if(setLength==0 && strlen(holder)==0){
			printf("\n{}");
			return;
		}
		
		setLengths[counter] = setLength+1;
		
		sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
		
		k = 0;
		
		start = 0;
		
		for(l=0;holder[l]!=00;l++){
			if(holder[l+1]==' '||holder[l+1]==00){
				holderToken = (char*)malloc((l+1-start)*sizeof(char));
				strncpy(holderToken,holder + start,l+1-start);
				sets[counter][k++] = atoi(holderToken);
				start = l+2;
			}
		}
		
		counter++;
		token = strtok(NULL,"x");
	}
	
	printf("\n{");
	cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
	printf("\b}");
	
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
	else
		processInputString(argV[1]);
	
	return 0;
}




Go: package main

import "fmt"

type pair [2]int

func cart2(a, b []int) []pair {
    p := make([]pair, len(a)*len(b))
    i := 0
    for _, a := range a {
        for _, b := range b {
            p[i] = pair{a, b}
            i++
        }
    }
    return p
}

func main() {
    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
    fmt.Println(cart2([]int{1, 2}, nil))
    fmt.Println(cart2(nil, []int{1, 2}))
}
Task: First-class functions

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

typedef double (*Class2Func)(double);
 

double functionA( double v)
{
   return v*v*v;
}
double functionB(double v)
{
   return exp(log(v)/3);
}
 

double Function1( Class2Func f2, double val )
{
    return f2(val);
}
 

Class2Func WhichFunc( int idx)
{
   return (idx < 4) ? &functionA : &functionB;
}
 

Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
 

double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
   return f1(f2(val));
}
 
typedef struct sComposition {
   Class2Func f1;
   Class2Func f2;
} *Composition;
 
Composition Compose( Class2Func f1, Class2Func f2)
{
   Composition comp = malloc(sizeof(struct sComposition));
   comp->f1 = f1;
   comp->f2 = f2;
   return comp;
}
 
double CallComposed( Composition comp, double val )
{
    return comp->f1( comp->f2(val) );
}

 
int main(int argc, char *argv[])
{
   int ix;
   Composition c;
 
   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
 
   for (ix=0; ix<4; ix++) {
       c = Compose(funcListA[ix], funcListB[ix]);
       printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
   }
 
   return 0;
}




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}