WeixiangYan/CodeTransOcean huggingface dataset:
Task: Proper divisors

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

int proper_divisors(const int n, bool print_flag)
{
    int count = 0;

    for (int i = 1; i < n; ++i) {
        if (n % i == 0) {
            count++;
            if (print_flag)
                printf("%d ", i);
        }
    }

    if (print_flag)
        printf("\n");

    return count;
}

int main(void)
{
    for (int i = 1; i <= 10; ++i) {
        printf("%d: ", i);
        proper_divisors(i, true);
    }

    int max = 0;
    int max_i = 1;

    for (int i = 1; i <= 20000; ++i) {
        int v = proper_divisors(i, false);
        if (v >= max) {
            max = v;
            max_i = i;
        }
    }

    printf("%d with %d divisors\n", max_i, max);
    return 0;
}




Go: package main

import (
    "fmt"
    "strconv"
)

func listProperDivisors(limit int) {
    if limit < 1 {
        return
    }
    width := len(strconv.Itoa(limit))
    for i := 1; i <= limit; i++ {
        fmt.Printf("%*d -> ", width, i)
        if i == 1 {
            fmt.Println("(None)")
            continue
        }
        for j := 1; j <= i/2; j++ {
            if i%j == 0 {
                fmt.Printf(" %d", j)
            }
        }
        fmt.Println()
    }
}

func countProperDivisors(n int) int {
    if n < 2 {
        return 0
    }
    count := 0
    for i := 1; i <= n/2; i++ {
        if n%i == 0 {
            count++
        }
    }
    return count
}

func main() {
    fmt.Println("The proper divisors of the following numbers are :\n")
    listProperDivisors(10)
    fmt.Println()
    maxCount := 0
    most := []int{1}
    for n := 2; n <= 20000; n++ {
        count := countProperDivisors(n)
        if count == maxCount {
            most = append(most, n)
        } else if count > maxCount {
            maxCount = count
            most = most[0:1]
            most[0] = n
        }
    }
    fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
    fmt.Println("namely", maxCount, "\b\n")
    for _, n := range most {
        fmt.Println(n)
    }
}
Task: XML_Output

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

const char *names[] = {
  "April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
  "Bubbly: I'm > Tam and <= Emily",
  "Burns: \"When chapman billies leave the street ...\"",
  "Short & shrift", NULL
};

int main()
{
  xmlDoc *doc = NULL;
  xmlNode *root = NULL, *node;
  const char **next;
  int a;

  doc = xmlNewDoc("1.0");
  root = xmlNewNode(NULL, "CharacterRemarks");
  xmlDocSetRootElement(doc, root);

  for(next = names, a = 0; *next != NULL; next++, a++) {
    node = xmlNewNode(NULL, "Character");
    (void)xmlNewProp(node, "name", *next);
    xmlAddChild(node, xmlNewText(remarks[a]));
    xmlAddChild(root, node);
  }

  xmlElemDump(stdout, doc, root);

  xmlFreeDoc(doc);
  xmlCleanupParser();
  
  return EXIT_SUCCESS;
}




Go: package main

import (
    "encoding/xml"
    "fmt"
)


func xRemarks(r CharacterRemarks) (string, error) {
    b, err := xml.MarshalIndent(r, "", "    ")
    return string(b), err
}



type CharacterRemarks struct {
    Character []crm
}

type crm struct {
    Name   string `xml:"name,attr"`
    Remark string `xml:",chardata"`
}

func main() {
    x, err := xRemarks(CharacterRemarks{[]crm{
        {`April`, `Bubbly: I'm > Tam and <= Emily`},
        {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
        {`Emily`, `Short & shrift`},
    }})
    if err != nil {
        x = err.Error()
    }
    fmt.Println(x)
}
Task: Plot coordinate pairs

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

#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};

void minmax(double *x, double *y,
	    double *minx, double *maxx, 
	    double *miny, double *maxy, int n)
{
  int i;

  *minx = *maxx = x[0];
  *miny = *maxy = y[0];
  for(i=1; i < n; i++) {
    if ( x[i] < *minx ) *minx = x[i];
    if ( x[i] > *maxx ) *maxx = x[i];
    if ( y[i] < *miny ) *miny = y[i];
    if ( y[i] > *maxy ) *maxy = y[i];
  }
}


#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2  
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)

#define MAXLABLEN 32

#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)

int main()
{
  int plotter, i;
  double minx, miny, maxx, maxy;
  double lx, ly;
  double xticstep, yticstep, nx, ny;
  double sx, sy;
  
  char labs[MAXLABLEN+1];

  plotter = pl_newpl("png", NULL, stdout, NULL);
  if ( plotter < 0 ) exit(1);
  pl_selectpl(plotter);
  if ( pl_openpl() < 0 ) exit(1);

  
  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);

  lx = maxx - minx;
  ly = maxy - miny;
  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
	    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
  
  
  xticstep = (ceil(maxx) - floor(minx)) / XDIV;
  yticstep = (ceil(maxy) - floor(miny)) / YDIV;

  pl_flinewidth(0.25);

  
  if ( lx < ly ) {
    sx = lx/ly;
    sy = 1.0;
  } else {
    sx = 1.0;
    sy = ly/lx;
  }

  pl_erase();

  
  pl_fbox(floor(minx), floor(miny),
	  ceil(maxx), ceil(maxy));

  
  pl_fontname("HersheySerif");
  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
    pl_fline(floor(minx), ny, ceil(maxx), ny);
    snprintf(labs, MAXLABLEN, "%6.2lf", ny);
    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
    PUSHSCALE(sx,sy);
    pl_label(labs);
    POPSCALE(sx,sy);
  }
  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
    pl_fline(nx, floor(miny), nx, ceil(maxy));
    snprintf(labs, MAXLABLEN, "%6.2lf", nx);
    FMOVESCALE(nx, floor(miny));
    PUSHSCALE(sx,sy);
    pl_ftextangle(-90);
    pl_alabel('l', 'b', labs);
    POPSCALE(sx,sy);
  }

  
  pl_fillcolorname("red");
  pl_filltype(1);
  for(i=0; i < NP; i++)
  {
    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
  }

  pl_flushpl();
  pl_closepl();
}




Go: package main

import (
  "fmt"
  "log"
  "os/exec"
)

var (
  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)

func main() {
  g := exec.Command("gnuplot", "-persist")
  w, err := g.StdinPipe()
  if err != nil {
    log.Fatal(err)
  }
  if err = g.Start(); err != nil {
    log.Fatal(err)
  }
  fmt.Fprintln(w, "unset key; plot '-'")
  for i, xi := range x {
    fmt.Fprintf(w, "%d %f\n", xi, y[i])
  }
  fmt.Fprintln(w, "e")
  w.Close()
  g.Wait()
}
Task: Regular expressions

C: #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>

int main()
{
   regex_t preg;
   regmatch_t substmatch[1];
   const char *tp = "string$";
   const char *t1 = "this is a matching string";
   const char *t2 = "this is not a matching string!";
   const char *ss = "istyfied";
   
   regcomp(&preg, "string$", REG_EXTENDED);
   printf("'%s' %smatched with '%s'\n", t1,
                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
   printf("'%s' %smatched with '%s'\n", t2,
                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
   regfree(&preg);
   
   regcomp(&preg, "a[a-z]+", REG_EXTENDED);
   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
   {
      
      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
                        (strlen(t1) - substmatch[0].rm_eo) + 2);
      memcpy(ns, t1, substmatch[0].rm_so+1);
      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
                strlen(&t1[substmatch[0].rm_eo]));
      ns[ substmatch[0].rm_so + strlen(ss) +
          strlen(&t1[substmatch[0].rm_eo]) ] = 0;
      printf("mod string: '%s'\n", ns);
      free(ns); 
   } else {
      printf("the string '%s' is the same: no matching!\n", t1);
   }
   regfree(&preg);
   
   return 0;
}




Go: package main
import "fmt"
import "regexp"

func main() {
  str := "I am the original string"

  
  matched, _ := regexp.MatchString(".*string$", str)
  if matched { fmt.Println("ends with 'string'") }

  
  pattern := regexp.MustCompile("original")
  result := pattern.ReplaceAllString(str, "modified")
  fmt.Println(result)
}
Task: Guess the number_With feedback (player)

C: #include <stdio.h>

int main(){
  int bounds[ 2 ] = {1, 100};
  char input[ 2 ] = "  ";
    
  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
    

  printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );

  do{
    switch( input[ 0 ] ){
      case 'H':
        bounds[ 1 ] = choice;
        break;
      case 'L':
        bounds[ 0 ] = choice;
        break;
      case 'Y':
        printf( "\nAwwwright\n" );
        return 0;
    }
    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;

    printf( "Is the number %d? (Y/H/L) ", choice );
  }while( scanf( "%1s", input ) == 1 );

  return 0;
}




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    lower, upper := 0, 100
    fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
    answer := sort.Search(upper-lower, func (i int) bool {
        fmt.Printf("Is your number less than or equal to %d? ", lower+i)
        s := ""
        fmt.Scanf("%s", &s)
        return s != "" && s[0] == 'y'
    })
    fmt.Printf("Your number is %d.\n", lower+answer)
}
Task: Hash from two arrays

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

#define KeyType const char *
#define ValType int

#define HASH_SIZE 4096


unsigned strhashkey( const char * key, int max)
{
    unsigned h=0;
    unsigned hl, hr;

    while(*key) {
        h += *key;
        hl= 0x5C5 ^ (h&0xfff00000 )>>18;
        hr =(h&0x000fffff );
        h = hl ^ hr ^ *key++;
    }
    return h % max;
}

typedef struct sHme {
    KeyType    key;
    ValType    value;
    struct sHme  *link;
} *MapEntry;

typedef struct he {
    MapEntry  first, last;
} HashElement;

HashElement hash[HASH_SIZE];
    
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);

void HashAddH( KeyType key, ValType value,
        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;

    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        (*copyVal)(&m_ent->value, value);
    }
    else {
        MapEntry last;
        MapEntry hme = malloc(sizeof(struct sHme));
        (*copyKey)(&hme->key, key);
        (*copyVal)(&hme->value, value);
        hme->link = NULL;
        last = hash[hix].last;
        if (last) {

            last->link = hme;
        }
        else
            hash[hix].first = hme;
        hash[hix].last = hme;
    }
}

int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;
    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        *val = m_ent->value;
    }
    return (m_ent != NULL);
}

void copyStr(const char**dest, const char *src)
{
    *dest = strdup(src);
}
void copyInt( int *dest, int src)
{
    *dest = src;
}
int strCompare( const char *key1, const char *key2)
{
    return strcmp(key1, key2) == 0;
}
    
void HashAdd( KeyType key, ValType value )
{
    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);
}

int HashGet(ValType *val, KeyType key)
{
    return HashGetH( val, key, &strhashkey, &strCompare);
}

int main() 
{
    static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
    static int valuList[] = {1,43,640, 747, 42, 42};
    int ix;

    for (ix=0; ix<6; ix++) {
        HashAdd(keyList[ix], valuList[ix]);
    }
    return 0;
}




Go: package main

import "fmt"

func main() {
    keys := []string{"a", "b", "c"}
    vals := []int{1, 2, 3}
    hash := map[string]int{}
    for i, key := range keys {
        hash[key] = vals[i]
    }
    fmt.Println(hash)
}
Task: Colour pinstripe_Display

C: #include<graphics.h>
#include<conio.h>

#define sections 4

int main()
{
	int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;
	initgraph(&d,&m,"c:/turboc3/bgi");
	
	maxX = getmaxx();
	maxY = getmaxy();
	
	for(y=0;y<maxY;y+=maxY/sections)
	{
		for(x=0;x<maxX;x+=increment)
		{
			setfillstyle(SOLID_FILL,(colour++)%16);
			bar(x,y,x+increment,y+maxY/sections);
		}
		increment++;
		colour = 0;
	}
	
	getch();
	closegraph();
	return 0;
}




Go: package main

import "github.com/fogleman/gg"

var palette = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}

func pinstripe(dc *gg.Context) {
    w := dc.Width()
    h := dc.Height() / 4
    for b := 1; b <= 4; b++ {
        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
            dc.SetHexColor(palette[ci%8])
            y := h * (b - 1)
            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
            dc.Fill()
        }
    }
}

func main() {
    dc := gg.NewContext(900, 600)
    pinstripe(dc)
    dc.SavePNG("color_pinstripe.png")
}
Task: Doomsday rule

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

typedef struct { 
    uint16_t year;
    uint8_t month;
    uint8_t day;
} Date;

bool leap(uint16_t year) {
    return year%4==0 && (year%100!=0 || year%400==0);
}

const char *weekday(Date date) {
    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
    static const char *days[] = {
        "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"
    };
    
    unsigned c = date.year/100, r = date.year%100;
    unsigned s = r/12, t = r%12;
    
    unsigned c_anchor = (5 * (c%4) + 2) % 7;
    unsigned doom = (s + t + (t/4) + c_anchor) % 7;
    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
    return days[(doom+date.day-anchor+7)%7];
}

int main(void) {
    const char *past = "was", *future = "will be";
    const char *months[] = { "",
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    };
    
    const Date dates[] = {
        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
        {2077,2,12}, {2101,4,2}
    };
    
    int i;
    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
        printf("%s %d, %d %s on a %s.\n",
            months[dates[i].month], dates[i].day, dates[i].year,
            dates[i].year > 2021 ? future : past,
            weekday(dates[i]));
    }
    
    return 0;
}




Go: package main

import (
    "fmt"
    "strconv"
)

var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

func anchorDay(y int) int {
    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}

func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }

var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}

func main() {
    dates := []string{
        "1800-01-06",
        "1875-03-29",
        "1915-12-07",
        "1970-12-23",
        "2043-05-14",
        "2077-02-12",
        "2101-04-02",
    }

    fmt.Println("Days of week given by Doomsday rule:")
    for _, date := range dates {
        y, _ := strconv.Atoi(date[0:4])
        m, _ := strconv.Atoi(date[5:7])
        m--
        d, _ := strconv.Atoi(date[8:10])
        a := anchorDay(y)
        f := firstDaysCommon[m]
        if isLeapYear(y) {
            f = firstDaysLeap[m]
        }
        w := d - f
        if w < 0 {
            w = 7 + w
        }
        dow := (a + w) % 7
        fmt.Printf("%s -> %s\n", date, days[dow])
    }
}
Task: Gray code

C: int gray_encode(int n) {
    return n ^ (n >> 1);
}

int gray_decode(int n) {
    int p = n;
    while (n >>= 1) p ^= n;
    return p;
}




Go: package main

import "fmt"

func enc(b int) int {
    return b ^ b>>1
}

func dec(g int) (b int) {
    for ; g != 0; g >>= 1 {
        b ^= g
    }
    return
}

func main() {
    fmt.Println("decimal  binary   gray    decoded")
    for b := 0; b < 32; b++ {
        g := enc(b)
        d := dec(g)
        fmt.Printf("  %2d     %05b   %05b   %05b  %2d\n", b, b, g, d, d)
    }
}
Task: Create a file on magnetic tape

C: #include<stdio.h>

int main()
{
	FILE* fp = fopen("TAPE.FILE","w");
	
	fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
	fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
	fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
	fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
	fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
	fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
	fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
	fprintf(fp,"EOF");
	
	fclose(fp);
	
	return 0;
}




Go: package main

import (
        "archive/tar"
        "compress/gzip"
        "flag"
        "io"
        "log"
        "os"
        "time"
)

func main() {
        filename := flag.String("file", "TAPE.FILE", "filename within TAR")
        data := flag.String("data", "", "data for file")
        outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
        gzipFlag := flag.Bool("gzip", false, "use gzip compression")
        flag.Parse()

        var w io.Writer = os.Stdout
        if *outfile != "" {
                f, err := os.Create(*outfile)
                if err != nil {
                        log.Fatalf("opening/creating %q: %v", *outfile, err)
                }
                defer f.Close()
                w = f
        }

        if *gzipFlag {
                zw := gzip.NewWriter(w)
                defer zw.Close()
                w = zw
        }

        tw := tar.NewWriter(w)
        defer tw.Close()
        w = tw
        tw.WriteHeader(&tar.Header{
                Name:     *filename,
                Mode:     0660,
                Size:     int64(len(*data)),
                ModTime:  time.Now(),
                Typeflag: tar.TypeReg,
                Uname:    "guest",
                Gname:    "guest",
        })

        _, err := w.Write([]byte(*data))
        if err != nil {
                log.Fatal("writing data:", err)
        }
}
Task: Sorting algorithms_Heapsort

C: #include <stdio.h>

int max (int *a, int n, int i, int j, int k) {
    int m = i;
    if (j < n && a[j] > a[m]) {
        m = j;
    }
    if (k < n && a[k] > a[m]) {
        m = k;
    }
    return m;
}

void downheap (int *a, int n, int i) {
    while (1) {
        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
        if (j == i) {
            break;
        }
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
        i = j;
    }
}

void heapsort (int *a, int n) {
    int i;
    for (i = (n - 2) / 2; i >= 0; i--) {
        downheap(a, n, i);
    }
    for (i = 0; i < n; i++) {
        int t = a[n - i - 1];
        a[n - i - 1] = a[0];
        a[0] = t;
        downheap(a, n - i - 1, 0);
    }
}

int main () {
    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%s", a[i], i == n - 1 ? "\n" : " ");
    heapsort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}




Go: package main

import (
  "sort"
  "container/heap"
  "fmt"
)

type HeapHelper struct {
    container sort.Interface
    length    int
}

func (self HeapHelper) Len() int { return self.length }

func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }
func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }

func (self *HeapHelper) Push(x interface{}) { panic("impossible") }
func (self *HeapHelper) Pop() interface{} {
    self.length--
    return nil 
}

func heapSort(a sort.Interface) {
    helper := HeapHelper{ a, a.Len() }
    heap.Init(&helper)
    for helper.length > 0 {
        heap.Pop(&helper)
    }
}

func main() {
    a := []int{170, 45, 75, -90, -802, 24, 2, 66}
    fmt.Println("before:", a)
    heapSort(sort.IntSlice(a))
    fmt.Println("after: ", a)
}
Task: Arrays

C:  char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}




Go: package main

import (
    "fmt"
)

func main() {
    
    
    
    var a [5]int

    
    
    fmt.Println("len(a) =", len(a))

    
    fmt.Println("a =", a)

    
    a[0] = 3
    fmt.Println("a =", a)

    
    fmt.Println("a[0] =", a[0])

    
    s := a[:4] 
    fmt.Println("s =", s)

    
    
    
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    
    
    s = s[:5]
    fmt.Println("s =", s)

    
    a[0] = 22
    fmt.Println("a =", a)
    fmt.Println("s =", s)

    
    s = append(s, 4, 5, 6)
    fmt.Println("s =", s)
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    
    a[4] = -1
    fmt.Println("a =", a)
    fmt.Println("s =", s)

    
    s = make([]int, 8)
    fmt.Println("s =", s)
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    
    
}
Task: Sierpinski carpet

C: #include <stdio.h>

int main()
{
	int i, j, dim, d;
	int depth = 3;

	for (i = 0, dim = 1; i < depth; i++, dim *= 3);

	for (i = 0; i < dim; i++) {
		for (j = 0; j < dim; j++) {
			for (d = dim / 3; d; d /= 3)
				if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
					break;
			printf(d ? "  " : "##");
		}
		printf("\n");
	}

	return 0;
}




Go: package main

import (
    "fmt"
    "strings"
    "unicode/utf8"
)

var order = 3
var grain = "#"

func main() {
    carpet := []string{grain}
    for ; order > 0; order-- {
        
        
        hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
        middle := make([]string, len(carpet))
        for i, s := range carpet {
            middle[i] = s + hole + s
            carpet[i] = strings.Repeat(s, 3)
        }
        carpet = append(append(carpet, middle...), carpet...)
    }
    for _, r := range carpet {
        fmt.Println(r)
    }
}
Task: Sorting algorithms_Bogosort

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

bool is_sorted(int *a, int n)
{
  while ( --n >= 1 ) {
    if ( a[n] < a[n-1] ) return false;
  }
  return true;
}

void shuffle(int *a, int n)
{
  int i, t, r;
  for(i=0; i < n; i++) {
    t = a[i];
    r = rand() % n;
    a[i] = a[r];
    a[r] = t;
  }
}

void bogosort(int *a, int n)
{
  while ( !is_sorted(a, n) ) shuffle(a, n);
}

int main()
{
  int numbers[] = { 1, 10, 9,  7, 3, 0 };
  int i;

  bogosort(numbers, 6);
  for (i=0; i < 6; i++) printf("%d ", numbers[i]);
  printf("\n");
}




Go: package main

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

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    rand.Seed(time.Now().UnixNano())
    fmt.Println("unsorted:", list)
    temp := make([]int, len(list))
    copy(temp, list)
    for !sort.IntsAreSorted(temp) {
        for i, v := range rand.Perm(len(list)) {
            temp[i] = list[v]
        }
    }
    fmt.Println("sorted!  ", temp)
}